← Back to all snippets
PHP

Randomly Select Elements from a PHP Array

Discover how to pick one or multiple random elements from a PHP array, useful for features like displaying random quotes, images, or test questions.

<?php
$quotes = [
    "The only way to do great work is to love what you do.",
    "Innovation distinguishes between a leader and a follower.",
    "Your time is limited, don't waste it living someone else's life.",
    "Stay hungry, stay foolish."
];

// Select a single random quote
$randomKey = array_rand($quotes);
$randomQuote = $quotes[$randomKey];
echo "Single random quote: " . $randomQuote . "

";

// Select multiple random quotes (e.g., 2)
$randomKeys = array_rand($quotes, 2);
$randomQuotes = [];
foreach ($randomKeys as $key) {
    $randomQuotes[] = $quotes[$key];
}
echo "Multiple random quotes:
";
print_r($randomQuotes);

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Shuffle the array to get a random order of all elements
shuffle($numbers);
echo "
Shuffled array:
";
print_r($numbers);
?>
How it works: The `array_rand()` function returns one or more random keys from an array. To retrieve the actual random values, you then access the array using these keys. For scenarios where you need to reorder the entire array randomly, the `shuffle()` function can be used; it modifies the array in place and re-indexes numeric keys.

Need help integrating this into your project?

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

Hire DigitalCodeLabs