PHP | array_rand() Function

This inbuilt function of PHP is used to fetch a random number of elements from an array. The element is a key and can return one or more than one key. On a practical basis, this is not that useful because the function uses pseudo-random number generator that is not suitable for cryptographic purposes.

Syntax:

array_rand($array, $num)

Parameters: The function takes only two arguments and are described below:



  1. $array (mandatory): This is a mandatory parameter and refers to the original input array.
  2. $num (optional): This parameter refers to the number of random numbers needed to be returned. This has to be greater than or equal to one otherwise E_WARNING is thrown along.

Return Value: This function returns the random generated values from the array. The number of returned elements depends on the value of the $num, assigned to the function.

Examples:

Input : 
$array = ("ram"=>"20", "krishna"=>"42", "aakash"=>"15")
$num = 2
Output :
Array
(
    [0] => ram
    [1] => aakash
)

Input :
$array = ("ram"=>"20", "krishna"=>"42", "aakash"=>"15")
Output : krishna

Below programs illustrates the array_rand() function in PHP:

  • In the below program we have passed our second parameter that specifies the number of elements to be returned.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
    // PHP function to illustrate the use 
    // of array_rand()
    $array = array("ram"=>"20", "krishna"=>"42"
                                "aakash"=>"15");
    $num = 2;
    print_r(array_rand($array, $num));
    ?>

    chevron_right

    
    

    Output:

    Array
    (
        [0] => ram
        [1] => krishna
    )
    
  • Now let’s see what will happen if we don’t pass the second parameter.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
    // PHP function to illustrate the 
    // use of array_rand()
    $array = array("ram"=>"20", "krishna"=>"42",
                                "aakash"=>"15");
    print_r(array_rand($array));
    ?>

    chevron_right

    
    

    Output:

    aakash
    

Reference:
http://php.net/manual/en/function.array-rand.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.