PHP

Select Random Elements or Shuffle an Array

Discover how to pick one or more random elements from an array or completely randomize the order of all elements using PHP's array_rand and shuffle functions.

<?php
$fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

// Get a single random key and its value
$randomKey = array_rand($fruits);
$randomFruit = $fruits[$randomKey];
echo "Random fruit: $randomFruit
"; // e.g., Random fruit: date

// Get multiple random keys and their values
$randomKeys = array_rand($fruits, 2);
$randomFruits = [];
foreach ($randomKeys as $key) {
    $randomFruits[] = $fruits[$key];
}
echo "Two random fruits: " . implode(', ', $randomFruits) . "
"; // e.g., Two random fruits: banana, cherry

// Completely shuffle the array in place
shuffle($fruits);
echo "Shuffled fruits: " . implode(', ', $fruits) . "
"; // e.g., Shuffled fruits: cherry, banana, elderberry, apple, date

$associativeArray = ['a' => 1, 'b' => 2, 'c' => 3];
// shuffle() only reorders values and re-indexes numeric keys, but not associative. Use array_rand for associative random picks.
$randomAssocKey = array_rand($associativeArray);
echo "Random associative key: $randomAssocKey, value: " . $associativeArray[$randomAssocKey] . "
";
How it works: `array_rand()` is used to pick one or more random keys from an array. When fetching a single key, it returns the key directly. For multiple keys, it returns an array of keys. You then use these keys to access the corresponding values. `shuffle()`, on the other hand, randomizes the order of all elements in an array in-place, modifying the original array. For numerically indexed arrays, it re-indexes the array. For associative arrays, it only shuffles values and loses the original string keys, re-indexing them numerically, so `array_rand()` is generally preferred for random access in associative arrays.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs