How to get a random key from a PHP array

How to get a random key from a PHP array

In this post, we will explain to you how to get a random value from the PHP array. We know that array is an essential part of any programming language and we required array in many conditions in the project to get the job done. Without an array managing the things inside the project is very tough.

Sometimes we encounter a situation where we need to get a random value from the array. For example – we want to display the list of user but the user should be different every time we refresh the page. At that time we need the different selected keys from an array.

array_rand() method in PHP will return the keys of the random entries.

What is array_rand()?

The array_rand() function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key.

This method takes two arguments: first will be the input array and the second argument specifies how many entries you want to pick.

Use of array_rand() method

Suppose we an array has 10 values in it, the second value in array_rand() will define how many values you want to get from that array. Let’s say you provide 8 in array_rand(array,8) then it will return back random 8 keys from an array.

Each time when you refresh the page you will get a different number. So let’s see how to get a random value from the PHP array.

Syntax:

array_rand(array,number)

Example 1

<!DOCTYPE html>
<html>
<body>
<?php
$a=array("red","yellow","brown","blue","yellow","green");
$random_keys=array_rand($a,3);
echo $a[$random_keys[0]]."<br>";
echo $a[$random_keys[1]]."<br>";
echo $a[$random_keys[2]];
?>
</body>
</html>

Output:

red
yellow
brown

Example 2

<!DOCTYPE html>
<html>
<body>

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"orange","f"=>"pink");
print_r(array_rand($a,2));
?>

</body>
</html>

Output

Array
(
    [0] => d
    [1] => e
)


Conclusion –

array_rand() method is very useful when you want to get random key values from the array. This method script is very useful in various situations like when we have to get data from a large array with the limited key value.

If you have any query related to this please free to comment us below we would happy to help you guys.

You can also check How to Convert a String to Array Using PHP Without Explode Function?