PHP array_rand() function with example

PHP array_rand() function with example

array_rand() work is utilized to get arbitrary keys from a cluster, it tends to be utilized to get single irregular key or exhibit of the keys by indicating the number of irregular keys.

Syntax:

  array_rand(array, [number]);

Example:

 Input:
    $arr = array("name" => "Amit", "age" => 21, "city" => "Gwalior");
   
    Output:
    random key: age

PHP Code:

<?php
    $arr = array("name" => "Amit", "age" => 21, "city" => "Gwalior");
    print("random key: " . array_rand($arr) ."\n");
    
    //generating an array of random keys
    print("array of random keys...\n");
    print_r(array_rand($arr, 2));
?>

Output

random key: age
array of random keys...
Array          
(              
    [0] => age 
    [1] => city
)

Recent Posts

error: Alert: Content is protected!!