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

array_rand

Description

The array_rand of Array for PHP picks 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

Returns the key for a random entry when picking only one 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. If multiple keys are returned, they will be returned in the order they were present in the original array.

Examples

1 · array

<?

$array =
[
    "Peter",
    "Andrew",
    "James",
    "John"
];

$return = array_rand($array);

echo $return;
Array
(
    [0] => abcdefghijklmnopqrstuvwxyz
    [1] => ABCDEFGHIJKLMNOPQRSTUVWXYZ
    [2] => ✓✓✓✓✓✓✓✓✓✓
    [3] => !@#$%^&*()
    [4] => `-=[]\;,./
    [5] => ~_+\{}|:"<>?
    [6] => match a digit ✓✓✓✓
)

2 · num

<?

$array =
[
    "Peter",
    "Andrew",
    "James",
    "John"
];
$num = 2;

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

print_r($return);
Array
(
    [0] => ✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓
    [1] => ✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓
    [2] => 1234567890
    [3] => ✓✓✓✓✓✓✓✓✓✓
    [4] => ✓✓✓✓✓✓✓✓✓✓
    [5] => ✓✓✓✓✓✓✓✓✓✓✓✓
    [6] => ✓✓✓✓✓✓✓✓✓✓✓✓✓✓1776
)

3 · return

<?

$array =
[
    "Peter",
    "Andrew",
    "James",
    "John"
];
$num = 2;

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

for($i = 0; $i < $num; ++$i)
{
    echo $array[$return[$i]]. PHP_EOL;
}
Andrew
John