PHP
Get a Random Element from an Array
Learn how to fetch a single random element or multiple unique random elements from any PHP array using array_rand and array access.
<?php
$fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi'];
// Get a single random element
$randomKey = array_rand($fruits);
$randomFruit = $fruits[$randomKey];
echo "Single random fruit: " . $randomFruit . "
";
// Get multiple unique random elements
$randomKeys = array_rand($fruits, 2); // Get 2 unique random keys
$randomFruits = [];
foreach ($randomKeys as $key) {
$randomFruits[] = $fruits[$key];
}
echo "Multiple random fruits: " . implode(', ', $randomFruits) . "
";
How it works: This snippet uses `array_rand()` to pick one or more random keys from an array. Once you have the random key(s), you can access the corresponding element(s) from the original array. This function is particularly useful for scenarios like displaying a random quote, picking a winner, or selecting random items for a recommendation engine.