Last updated on January 24th, 2023 at 08:14 am
This is a very simple script that display text or quotes randomly when user refresh page. Steps to write the code involves,
- Defining quotes or texts inside an array first
- Depending on the size of the array use rand() function
- Display it using echo command
Here is the complete PHP script
<?php
$quote = array(
1 => "Text To Display 1",
2 => "Text To Display 2",
3 => "It Works Display 3",
4 => "The Next Display 4",
5 => "Again Display 5",
6 => "Visit Mistonline.in For All Kind Of Tutorials Display 6"
);
$randnum = rand(1,6);
echo "<div id='random' style='border:solid 1px; padding:5px; margin:5px;'>Random Quote - <b>$quote[$randnum]</b></div>";
?>
As you can see I have 6 elements in the array and using rand(1,6) I can display it.
Now if you want to just define the array and dynamically add the max number instead of manually adding 6 in rand(1,6) just use this
$num = count($quote);
$randnum = rand(1,$num);
Here we are counting the number of elements in the array using count() thereby dropping the need of adding the maximum number inside the rand()
That was a cool and awesome post more effective…