Skip to content

Instantly share code, notes, and snippets.

@simtabi
Forked from zgulde/php_random_array_element.md
Created February 24, 2021 14:34
Show Gist options
  • Save simtabi/c18631bbdb4d0edaa268e353b3075b95 to your computer and use it in GitHub Desktop.
Save simtabi/c18631bbdb4d0edaa268e353b3075b95 to your computer and use it in GitHub Desktop.
how to get a random array element in php

Getting a random element from an array

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 index 0, and the last element, 5 is at index 4
  • 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)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment