The
array_rand() array function in PHP will select one or more keys from an array at random. You can use the array's keys to access the values from the random keys selected, as shown in the examples below.
Example 1 - Select one key from the array at random
<?php
$targetArray = array("Sara","Cindy","Julie","Megan");
$rand = array_rand($targetArray);
echo $targetArray[$rand];
?>
Cindy
Example 2 - Select multiple keys at random
<?php
$targetArray = array("Sara","Cindy","Julie","Megan");
$rand = array_rand($targetArray, 2);
foreach ($rand as $key => $value) {
echo "$key - <strong>" . $targetArray[$value] . "</strong><br />";
}
?>
0 - Julie
1 - Megan