How To Randomly Retrieve a Value from an Array

Q

How To Randomly Retrieve a Value from an Array? - PHP Script Tips - PHP Built-in Functions for Arrays

✍: FYIcenter.com

A

If you have a list of favorite greeting messages, and want to randomly select one of them to be used in an email, you can use the array_rand() function. Here is a PHP example script:

<?php
$array = array("Hello!", "Hi!", "Allo!", "Hallo!", "Coucou!");
$key = array_rand($array);
print("Random greeting: ".$array[$key]."\n");
?>

This script will print:

Random greeting: Coucou!

2007-04-21, 5386👍, 0💬