In this post, we are going to see how to write a simple PHP program to generate Random Background Color and for every refresh, we are going to change the background color.
Let’s write the PHP snippet first which gives us a random color code every time we refresh the page.
1 2 3 4 5 6 |
<?php $colors = ['#162B3F', '#20CAC2', '#5C9559', '#E7B5DC', '#EE65F2', '#9C9BFE', '#888C71', '#4E1BE2', '#04650E', '#BF6780']; $random_color = $colors[array_rand($colors)]; ?> |
Now we have the color code, let us set the background color in the <body> tag.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php $colors = ['#162B3F', '#20CAC2', '#5C9559', '#E7B5DC', '#EE65F2', '#9C9BFE', '#888C71', '#4E1BE2', '#04650E', '#BF6780']; $random_color = $colors[array_rand($colors)]; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Random Background Color using PHP - Tutorialsmade.com</title> </head> <body style="background: <?=$random_color;?>"> <h1 style="color: white; text-align:center;">Random Background Color using PHP</h1> <h2 style="color: yellow; text-align:center;">Refresh the page to see a different Background Color<h2> </body> </html> |
That’s it. We have a PHP & HTML script that produces Random Background Color every time when we refresh the page. You can check the demo from the below link.