For day 20 of 21 in the “PHP Function of the day” series, I’m going to look at array_rand(). The function takes a required array and an optional number of random keys to return. It returns a random key (not the value).
Let’s take a look.
<?php
$names = array(“Joe”,”Jim”,”Sarah”,”Jill”);
$numbers = array(1,2,3,4,5,6,7,8,9);
$names_rand_keys = array_rand($names,3);
$numbers_rand_keys = array_rand($numbers);
echo $names[$names_rand_keys[0]].”<br />”;
echo $names[$names_rand_keys[1]].”<br />”;
echo $names[$names_rand_keys[2]].”<br />”;
print_r($numbers[$numbers_rand_keys]);
?>
As you can see, you can also probably just use rand() and just limit it to the size of the array.