Output a random string on each page load in PHP

To output a random string from an array on each page load you can use the array_rand function in PHP.

//add your strings to the array
$input = array(
"Where friendships flourish and grow",
"Where you are treated with respect",
"Where people are helpful and sincere",
"Where you feel safe and at home"
//output a random string
echo '<p><em class="statement">' . $input[array_rand($input)] . '</em></p>'; ?>
view raw random_string.php hosted with ❤ by GitHub

So in the above snippet the array is created and assigned to the $input variable, it is then output using echo and passing the $input variable initially to array_rand and the result of that being assigned that back to the $input variable, each page load will randomise the output.

Leave a Comment