PHP Tutorial

PHP Examples

PHP Practice

PHP Array array_rand() Function (With Examples)

In this tutorial, we will learn about the PHP array_rand() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP array_rand() Function

The 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

The syntax of the array_rand() function:

array_rand(array, [number]);

Parameters

The parameters of the array_rand() function:

  • 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 mpageTU random key i.e. an array of keys.

Return Value

The return type of this method is int|string|array, it returns the key for a random entry. [Source]

Sample Input/Output

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

PHP array_rand() Function Example

<?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

The output of the above example is:

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

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.