How to perform multiple 5‑card draws from a shuffled 52‑card deck in PHP

1 Answer

0 votes
/*
A standard deck of 52 playing cards consists of four suits:
spades (♠), hearts (♥), diamonds (♦), and clubs (♣).

Each suit contains 13 ranks:
Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King.

Cards of spades and clubs are black, while hearts and diamonds are red.

Color is informational only — it does not affect shuffling or random selection.
*/

/*
    This program performs multiple draws of 5 random cards from a 52‑card deck
    WITHOUT duplicates across draws.

    It uses:
    - Arrays for ranks, suits, and the deck
    - shuffle() for efficient randomization (Fisher–Yates internally)
    - Functions for clean structure

    Algorithm:
    1. Build a full deck (52 cards)
    2. For each draw:
       a. Shuffle the remaining deck
       b. Draw 5 cards
       c. Remove them from the deck
*/

function buildDeck(): array {
    $ranks = ["2","3","4","5","6","7","8","9","10","J","Q","K","A"];
    $suits = ["Clubs", "Diamonds", "Hearts", "Spades"];

    $deck = [];

    foreach ($suits as $suit) {
        foreach ($ranks as $rank) {
            $deck[] = "$rank of $suit";
        }
    }

    return $deck;
}

function drawFive(array &$deck, int $drawNumber): void {
    // Shuffle the remaining deck before this draw
    shuffle($deck);

    echo "Draw #$drawNumber:\n";
    for ($i = 0; $i < 5; $i++) {
        echo "  {$deck[$i]}\n";
    }
    echo "\n";

    // Remove drawn cards
    array_splice($deck, 0, 5);
}

function main(): void {
    // Number of draws
    $draws = 3;

    // Build the deck
    $deck = buildDeck();

    // Perform multiple draws (no duplicates)
    for ($i = 1; $i <= $draws; $i++) {
        if (count($deck) < 5) {
            echo "Not enough cards left for draw #$i.\n";
            break;
        }

        drawFive($deck, $i);
    }
}

main();


/*
run:

Draw #1:
  Q of Clubs
  9 of Clubs
  Q of Spades
  9 of Spades
  A of Hearts

Draw #2:
  Q of Hearts
  10 of Clubs
  5 of Clubs
  J of Spades
  7 of Clubs

Draw #3:
  K of Clubs
  6 of Diamonds
  A of Diamonds
  K of Diamonds
  K of Spades
  
*/

 



answered 10 hours ago by avibootz

Related questions

...