Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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"); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page