Generate random RGB color code in PHP
Greetings Programmers, in this tutorial we will see how to generate random RGB color code in PHP.
The RGB color model stands for Red, Green, and Blue respectively which are the primary colors of light. These colors when mixed in different proportions create a new set of colors which can be helpful for a designer to complete its design.
This RGB color model consists of a set of three values ranging from 0 to 255 with 0 and 255 inclusive.
Generating Random RGB Colors in PHP
We can generate random colors using a random function between the range 0 to 255 for the main primary colors red, green, and blue.
function rndRGBColorCode() { return 'rgb(' . rand(0, 255) . ',' . rand(0, 255) . ',' . rand(0, 255) . ')'; #using the inbuilt random function }
We use the above function to generate the random colors in RGB format by concatenating them with the corresponding values in a specified range of values.
We can call the following function above and generate the colors.
$rndColor = rndRGBColorCode(); #function call echo $rndColor;
Output for the following
rgb(242,104,192)
Using random color generated for the background of web page
In the following program, we will generate a random RGB color using random values and string manipulations.
<?php #generate random rgb color function rndRGBColorCode() { return 'rgb(' . rand(0, 255) . ',' . rand(0, 255) . ',' . rand(0, 255) . ')'; #using the inbuilt random function } #driver $rndColor = rndRGBColorCode(); #function call $valPrint = '<body><h1 align = "center">The color is: ' . $rndColor . '</h1></body>'; #value print $colorPage = sprintf('<style type="text/css"> body {background-color: %s} </style>', $rndColor); #bg color shade echo $valPrint . $colorPage; #printing result ?>
Output
Explanation
The ‘rndRGbColorCode()’ function generates the random set of three values ranging from 0 to 255 and concatenated with the string ‘RGB’ using string manipulations. We call the function and print the randomly generated RGB value. Correspondingly, we set the background color using HTML and CSS syntax with the randomly generated RGB color code. On each refresh of the page, random colors are generated and depicted in the background of the webpage as well as the code is displayed over it.
Leave a Reply