PHP

Select N Unique Random Elements from a PHP Array

Learn how to pick a specified number of unique, random elements from an existing PHP array without replacement, useful for quizzes or lottery systems.

<?php
function get_random_unique_elements(array $array, int $numElements): array
{
    if ($numElements <= 0) {
        return [];
    }
    if ($numElements >= count($array)) {
        // Return all elements if numElements is greater or equal to array size
        // Shuffle them if desired, but here we just return all
        shuffle($array);
        return $array;
    }

    // array_rand returns keys, so map them to values
    $randomKeys = array_rand($array, $numElements);
    $selectedElements = [];
    // Ensure randomKeys is an array even if numElements is 1
    if (!is_array($randomKeys)) {
        $randomKeys = [$randomKeys];
    }
    foreach ($randomKeys as $key) {
        $selectedElements[] = $array[$key];
    }
    return $selectedElements;
}

$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.",
    "Logic will get you from A to B. Imagination will take you everywhere.",
    "The best way to predict the future is to create it."
];

$randomQuotes = get_random_unique_elements($quotes, 3);
echo "Randomly selected quotes:
";
foreach ($randomQuotes as $quote) {
    echo "- " . $quote . "
";
}

echo "
Selecting 0 elements:
";
print_r(get_random_unique_elements($quotes, 0));

echo "
Selecting more elements than available:
";
print_r(get_random_unique_elements($quotes, 10));
?>
How it works: This function selects a specified number of unique, random elements from an input array. It uses `array_rand` to get random keys, ensuring that no element is picked more than once. This is useful for scenarios like displaying random testimonials, generating quiz questions, or any case where you need a subset of unique items from a larger collection.

Need help integrating this into your project?

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

Hire DigitalCodeLabs