PHP

Select Multiple Random Items from PHP Array Without Replacement

Learn how to randomly select a specified number of unique items from a PHP array, ensuring no duplicates are picked, useful for lotteries or quizzes.

<?php

$deckOfCards = ['Ace', 'King', 'Queen', 'Jack', '10', '9', '8', '7', '6', '5', '4', '3', '2'];
$numberOfCardsToDraw = 5;

$randomKeys = array_rand($deckOfCards, $numberOfCardsToDraw);
$drawnCards = [];

if (!is_array($randomKeys)) { // array_rand returns a single key if only one is requested
    $randomKeys = [$randomKeys];
}

foreach ($randomKeys as $key) {
    $drawnCards[] = $deckOfCards[$key];
}

echo "Drawn Cards:
";
print_r($drawnCards);

// Example: Drawing 2 cards
$twoCards = [];
$randomTwoKeys = array_rand($deckOfCards, 2);
foreach ($randomTwoKeys as $key) {
    $twoCards[] = $deckOfCards[$key];
}
cho "
Drawn Two Cards:
";
print_r($twoCards);

?>
How it works: This snippet demonstrates how to draw multiple unique random elements from an array without replacement. `array_rand()` is used to get a specified number of random keys from the array. These keys are then used to retrieve the corresponding values, effectively selecting random items without the possibility of picking the same item twice.

Need help integrating this into your project?

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

Hire DigitalCodeLabs