Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

array_rand

Description

The array_rand of Array for PHP pick one or more random keys out of an array.

Syntax

array_rand(array $array, int $num = 1): int|string|array

Parameters

array

The input array.

num

Specifies how many entries should be picked.

Return

When picking only one entry, array_rand() returns the key for a random entry. Otherwise, an array of keys for the random entries is returned. This is done so that random keys can be picked from the array as well as random values. Trying to pick more elements than there are in the array will result in an E_WARNING level error, and NULL will be returned.

Examples

1 · array

<?

$array = array("Peter", "Andrew", "James", "John");

$return = array_rand($array);

echo $return;

?>
2

2 · num

<?

$array = array("Peter", "Andrew", "James", "John");
$num = 2;

$return = array_rand($array, $num);

print_r($return);

?>
Array
(
    [0] => 2
    [1] => 3
)

3 · return

<?

$array = array("Peter", "Andrew", "James", "John");
$num = 2;

$return = array_rand($array, $num);

for($i = 0; $i < $num; ++$i)
{
    echo $array[$return[$i]] . "\n";
}

?>
Peter
Andrew
HomeMenu