Home » PHP

PHP array_rand() function with example

PHP array_rand() function: Here, we are going to learn about the array_rand() function with example in PHP.
Submitted by IncludeHelp, on February 15, 2019

PHP array_rand() function

array_rand() function is used to get random keys from an array, it can be used to get single random key or array of the keys by specifying the number of random keys.

Syntax:

    array_rand(array, [number]);

Here,

  • array is an input array, we have to get the random keys from it.
  • number is the total number of random keys, it is used to get more than one random key i.e. an array of keys.

Examples:

    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
)





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.