Array Functions

PHP array_rand() Function

Topic: PHP Array ReferencePrev|Next

Description

The array_rand() function returns one or more random keys from an array.

The following table summarizes the technical details of this function.

Return Value: Returns a random key or an array of random keys from an array.
Changelog:

Since PHP 7.1.0, the internal randomization algorithm has been changed to use the Mersenne Twister random number generator instead of the libc rand function.

Since PHP 5.2.1, the resulting array of keys is no longer shuffled.
Version: PHP 4+

Syntax

The basic syntax of the array_rand() function is given with:

array_rand(array, num);

The following example shows the array_rand() function in action.

<?php
// Sample array
$colors = array("red", "green", "blue", "yellow", "orange");
    
// Getting two random keys from the colors array
$rand_keys = array_rand($colors, 2);
print_r($rand_keys);

// Printing corresponding values from colors array
echo $colors[$rand_keys[0]] . "<br>";
echo $colors[$rand_keys[1]];
?>

Note: If you try to pick more elements than there are in the array, the array_rand() function will throw an E_WARNING level error, and NULL will be returned.


Parameters

The array_rand() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to work on.
num Optional. Specifies how many random keys to return.

More Examples

Here're some more examples showing how array_rand() function actually works:

This function can also be used with the associative array, here's an example:

<?php
// Sample array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "d"=>"dog");
    
// Getting three random keys from the alphabets array
$rand_keys = array_rand($alphabets, 3);
print_r($rand_keys);

// Printing corresponding values from alphabets array using loop
foreach($rand_keys as $key){
    echo $alphabets[$key] . "<br>";
}
?>
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties