I l@ve RuBoard Previous Section Next Section

array_rand

mixed array_rand(array array, [int num_elements]) 

array

Array from which to pick random elements

num_elements

Number of elements to pick at random

Returns one or more keys at random from an array.

Returns:

Key or array of keys of random elements of an array; NULL on failure

Description:

This function selects num_elements elements at random from the array given by array and returns their keys as elements in a new array. If num_elements is 1 or omitted, a single key is returned. Otherwise, an indexed array is returned; the selected keys are the element values in the returned array.

Since array_rand() internally uses the rand() function, you should use srand() before calling array_rand() to ensure the greatest possible randomness.

Version:

PHP 4 since 4.0.0

See also:

rand() 
srand() 
shuffle() 

Example:

Select random elements from an array
$array_1 = array( 'one' => 'Dave', 
                  'two' => 'Piia', 
                  'three' => 'Leigh', 
                  'four' => 'Adam', 
                  'five' => 'Leigh'); 

Output (just an example; random results will be different): 
Array 
(
    [0] => one 
    [1] => four 
) 
    I l@ve RuBoard Previous Section Next Section