How to Write a PHP script that changes the Background colour on Page Refresh
Hello, i'm Majiyd and in this article, i',m going to show you how to write a simple PHP script that would change the background colour of your webpage anytime the page is reloaded.
First, we set up a simple index.php file and run on localhost
"<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Changing the background colour</title>
</head>
<body>
<p>The background colour of this page changes anytime this page is refreshed</p>
</body>
</html>"
Next, we add a php tag to the file and the initialise an array. In this array, we'll add all the colours that we want to background to be able to change to.
<?php
$colours = array("red", "green", "blue", "white", "pink", "gold")
?>
$colours is the array that consists of all the colours. Next, we initialise an integer $num which is the number of available colours.
<?php
$colours = array("red", "green", "blue", "white", "pink", "gold");
$num = count($colours) - 1;
?>
Count is an in-built PHP function for getting the number of elements in an array. You probably noticed that we subtracted one from count($colours) to get $num, this is because in PHP, 0 is considered the first number, not 1.
Each colour in the $colours array can be printed to the screen by calling $colours with an index corresponding to the position of the colour in the array. For example
$colours[0] refers to red
$colours[1] refers to green
$colours[5] refers to gold
A more practical example would be to execute the simple script show below
<?php $colours = array("red", "green", "blue", "white", "pink", "gold"); $num = count($colours) - 1; echo $colours[0];
echo "<br/>";
echo $colours[1];echo "<br/>";
echo $colours[5]; ?>
The result is:
Now we change the background colour by echoing a random colour from our array into a css style tag present our page as shown below:
<?php
$colours = array("red", "green", "blue", "white", "pink", "gold");
$num = count($colours) - 1;
$background_colour = $colours[rand(0,$num)];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Changing the background colour</title>
<style type="text/css">
body{
background-color: <?php echo $background_colour;?>
}
</style>
</head>
<body>
<p>The background colour of this page changes anytime this page is refreshed</p>
</body>
</html>
No comments:
Post a Comment