Home >Backend Development >PHP Tutorial >How do I retrieve a random element from an array in PHP?
Retrieve a Random Array Element
When dealing with arrays in PHP, it may be necessary to select a random item from the array. Consider the array $items:
$items = [523, 3452, 334, 31, ... 5346];
Solution: Utilize array_rand()
To retrieve a random element from $items, use the array_rand() function:
echo $items[array_rand($items)];
Explanation of array_rand()
array_rand() takes an array as input and returns a random index from that array. Combining this result with array index access using brackets, we can retrieve the corresponding random element from $items.
Additional Notes:
The above is the detailed content of How do I retrieve a random element from an array in PHP?. For more information, please follow other related articles on the PHP Chinese website!