Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to get random value out of an array in PHP?
In PHP, you can get a random value from an array using the array_rand() function. This function returns a random key from the array, which you can then use to access the corresponding value.
Syntax
array_rand(array, number)
Parameters:
- array − The input array
- number − Optional. Number of random keys to return (default is 1)
Getting Single Random Value
Here's how to get one random value from an array ?
<?php
$arr = array("p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115", "u"=>"103", "v"=>"105", "w"=>"125");
echo "Array values ...
";
echo "Value 1 = " . $arr["p"] . "
";
echo "Value 2 = " . $arr["q"] . "
";
echo "Value 3 = " . $arr["r"] . "
";
echo "Value 4 = " . $arr["s"] . "
";
echo "Value 5 = " . $arr["t"] . "
";
echo "Value 6 = " . $arr["u"] . "
";
echo "Value 7 = " . $arr["v"] . "
";
echo "Value 8 = " . $arr["w"] . "
";
echo "Random value from array = " . $arr[array_rand($arr)];
?>
Array values ... Value 1 = 150 Value 2 = 100 Value 3 = 120 Value 4 = 110 Value 5 = 115 Value 6 = 103 Value 7 = 105 Value 8 = 125 Random value from array = 110
Getting Multiple Random Values
You can also get multiple random values by specifying the number as the second parameter ?
<?php
$arr = array("p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115", "u"=>"103", "v"=>"105", "w"=>"125");
echo "Array values ...
";
echo "Value 1 = " . $arr["p"] . "
";
echo "Value 2 = " . $arr["q"] . "
";
echo "Value 3 = " . $arr["r"] . "
";
echo "Value 4 = " . $arr["s"] . "
";
echo "Value 5 = " . $arr["t"] . "
";
echo "Value 6 = " . $arr["u"] . "
";
echo "Value 7 = " . $arr["v"] . "
";
echo "Value 8 = " . $arr["w"] . "
";
$res = array_rand($arr, 2);
echo "Random values from array...
";
echo $arr[$res[0]] . " " . $arr[$res[1]];
?>
Array values ... Value 1 = 150 Value 2 = 100 Value 3 = 120 Value 4 = 110 Value 5 = 115 Value 6 = 103 Value 7 = 105 Value 8 = 125 Random values from array... 150 115
Working with Indexed Arrays
For simple indexed arrays, the process is even more straightforward ?
<?php
$fruits = array("apple", "banana", "orange", "grape", "mango");
echo "All fruits: " . implode(", ", $fruits) . "
";
echo "Random fruit: " . $fruits[array_rand($fruits)];
?>
All fruits: apple, banana, orange, grape, mango Random fruit: orange
Conclusion
The array_rand() function is the most efficient way to get random values from PHP arrays. It returns random keys that you use to access the corresponding values, and supports both single and multiple random selections.
Advertisements
