, , , ,

How to get a random value from a PHP array? explain with example

Posted by

Random value from a PHP Array

In this query, you will get two functions to get random values out of an array in PHP. The shuffle() and array_rand() function is used to get random values out of an array.

Example:

Input : $arr = (“a”=>”31”, “b”=>”41”, “c”=>”9”, “d”=>”30”)

// Get one random value
Output: 9

Input : $arr = (“a”=>”31”, “b”=>”41”, “c”=>”9”, “d”=>”30”)

// Get two random values
Output: 31 41
Process 1: This method describes the shuffle() function to get a random value out of an array in PHP.
PHP | shuffle() Function: The shuffle() Function is an inbuilt function in PHP that is used to shuffle or randomize the order of the elements in an array. This function assigns new keys for the elements in the array. It will also remove any existing keys, rather than just reordering the keys and assigns numeric keys starting from zero.

Example:

<?php
 
// Declare an associative array
$arr = array( "a"=>"31", "b"=>"41", "c"=>"9", "d"=>"30" );
 
// Use shuffle function to randomly assign numeric
// key to all elements of array.
shuffle($arr);
 
// Display the first shuffle element of array
echo $arr[0];
 
?>

Output:
41

In the above example the keys of associative array have been changed. The shuffle() function has randomly assigned keys to elements starting from zero.
As shuffle() permanently change the keys of an array.

Process 2: Use the array_rand() function to get a random value out of an array in PHP.
PHP | array_rand() Function: The array_rand() function is an inbuilt function in PHP which 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.

This function accepts two parameters $array and $num. The $array variable store the array elements and $num parameter holds the number of elements need to fetch. By default value of this parameter is 1.

Example :

<?php
 
// Declare an associative array
$arr = array( "a"=>"31", "b"=>"41", "c"=>"9", "d"=>"30" );
 
// Use array_rand function to returns random key
$key = array_rand($arr);
 
// Display the random array element
echo $arr[$key];
 
?>

Output:
31

In the above example, we didn’t explicitly specified the value for second parameter so by default the value is 1, and array_rand() will return one random key.

Example : This example explicitly specify the value for second parameter so the array_rand() function will return the array of random keys.

<?php
 
// Declare an associative array
$arr = array( "a"=>"31", "b"=>"41", "c"=>"9", "d"=>"30" );
 
// It specify the number of element
$num = 2;
  
// It returns array of random keys
$keys = array_rand( $arr, $num );
 
// Display the array element
echo $arr[$keys[0]]." ".$arr[$keys[1]];
 
?>

Output:
31 9

guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x