PHP array_rand() Function

PHP array_rand() Function returns one or more random key from an array. The array_rand() is a built-in function of PHP.

Syntax :

array_rand($array, $number);

Parameter,

$array : Required  It is type of array parameter.
$number : Optional. It specifies how many random keys to return.

Let's see below example to understand php array_rand() Function in details.

Return : A array_rand() Function returns one key randomly from an array if number parameter is not specified.

Example :

<?php
echo "<br><br>It returns one random key from array animals.<br>";
$animals= array("a"=>"Dog", "b"=>"Cat", "c"=>"Cow", "d"=>"Fox", "e"=>"Lion");
$arr=array_rand($animals);
print_r($arr);

echo "<br><br>It returns two random keys from array animals.<br>";
$animals= array("a"=>"Dog", "b"=>"Cat", "c"=>"Cow", "d"=>"Fox", "e"=>"Lion");
$arr=array_rand($animals, 2);
print_r($arr);
?>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

70583