Random Background Colour PHP
In this article , we will try to generate a random back ground colour using PHP, when the Browser is being refresh.
Follow the Step by Step below
- First we will create a function , i named it “GenerateColor()”
- Then I will assign the First value”#” to $randomcolor
- I assign an initial value for $i , this will be applied into the do, while loop
- I create a do , while loop, do when $i value is less than 6,
- Why is it 6 as the Colour code have 6 digit or alphabet + the “#”sign
- The “rand()” function is used , limit between 0 to 15
- Why is it 15 as Hex digit counts from 0 to 9 , starting from 10 to 15 it will be A to F
- I create a switch in the the do while loop by switching the $RandomNumber
- The Switch will reassign the Value for 10= A , 11=B, 12=C ,13=D, 14=E, 15=F.
- In the Do while loop , the I is incremented
- The Value of $randomcolor = ‘#’ is append or concatenate to the $RandomNumber Value.
Refer the Code Below for the Random Background Colour PHP Code
<?php function GenerateColor(){ $randomcolor = '#'; $i=0; do{ $RandomNumber = rand(0,15); switch ($RandomNumber) { case 10:$RandomNumber='A'; break; case 11:$RandomNumber='B'; break; case 12:$RandomNumber='C'; break; case 13:$RandomNumber='D'; break; case 14:$RandomNumber='E'; break; case 15:$RandomNumber='F'; break; } $randomcolor .= $RandomNumber; $i++; }while($i<6); //$rcolor = '#FF0000'; return $randomcolor ; } echo '<div style="padding:20px;background-color:'.GenerateColor().';color:'.GenerateColor().'"> Random background color</div>'; ?>
Check out Array Function in PHP here