Name

array_rand()

Synopsis

    mixed array_rand ( array arr [, int amount] )

The array_rand() function picks out one or more random values from an array. It takes an array to read from, then returns either one random key or an array of random keys from inside there. The advantage to array_rand() is that it leaves the original array intact, so you can just use that randomly chosen key to grab the related value from the array.

There is an optional second parameter to array_rand() that allows you to specify the number of elements you would like returned. These are each chosen randomly from the array, and are not necessarily returned in any particular order. The function also has these attributes:

  • It returns the keys in your array. If these aren't specified, the default integer indexes are used. To get the value out of the array, look up the value at the key.

  • If you ask for one random element, or do not specify parameter two, you will get a single randomly chosen variable back.

  • If you ask for more than one random element, you will receive an array of variables back.

  • If you ask for more random elements than there are in the array, you will get an error.

  • If you request more than one random element, it will not return duplicate elements.

  • If you want to read most or all of the elements from your array in a random order, use a mass randomizer like shuffle(), as it is faster.

With that in mind, here's an example of array_rand() in action:

 $natural_born_killers = array("lions", "tigers", "bears", "kittens"); ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.