Computer >> Computer tutorials >  >> Programming >> PHP

array_rand() function in PHP


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

Syntax

array_rand(arr, count)

Parameters

  • arr − the specified array

  • count − the number of random keys to return

Return

The array_rand() function returns a random key. You can specify if you want an array of random keys (more than one key) to be returned.

Example

The following is an example −

<?php
$arr = array("p"=>"mobile","q"=>"laptop","r"=>"tablet");
print_r(array_rand($arr,1));
?>

Output

r

Let us see another example wherein more than one keys are returned −

Example

<?php
$arr = array("p"=>"mobile","q"=>"laptop","r"=>"tablet");
print_r(array_rand($arr,2));
?>

Output −

Array (
   [0] => p
   [1] => q
)