tldr: the function at the end of this gist will give you a random array element
Figuring out how to get a random array element will give a better understanding of how PHP works, as well as how arrays work in general.
Lets start with this code:
$numbers = [1, 2, 3, 4, 5];
And get a random number out of it!
First we need a random index out of the array.
Remember that arrays are 0 - indexed, and the largest index is one less than the number of items in the array.
Using our $numbers
array as an example:
$numbers = [1, 2, 3, 4, 5];
// ^ ^ ^ ^ ^
// indexes | | | | |
// 0 1 2 3 4
- The first element,
1
is at index0
, and the last element,5
is at index4
- The total number of elements in the array is 5
- 4, the greatest index in the array, is one less than 5, the total number of elements in the array.
Keeping this in mind, lets get a random index from our $numbers
array. We'll use PHP's build-in count
function that returns the number of items in an array.
$randomIndex = mt_rand(0, count($numbers) - 1);
Luckily, PHP has a built-in function to do all this thinking for us, array_rand
. All we have to do is give array_rand
an array, and it will return us a random index in it. We could rewrite our code like so.
$randomIndex = array_rand($numbers);
Now we need to access the element at our random index.
$randomNumber = $numbers[$randomIndex];
And we have a random number from our array!
Lets pull this code out into a separate function that we can reuse.
function getRandomArrayElement($array)
{
$randomIndex = array_rand($array);
$randomElement = $array[$randomIndex];
return $randomElement;
}
Now to get a random number from our $numbers
array, all we would have to do is call our function.
$randomNumber = getRandomArrayElement($numbers);
We could also rewrite our function to be a one liner:
function getRandomArrayElement($array)
{
return $array[array_rand($array)];
}