Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

4.21. Shuffling a Deck of Cards

Problem

You want to shuffle a deck of cards and deal them out.

Solution

Create a array of 52 integers, shuffle them, and map them to cards:

$suits = array('Clubs', 'Diamonds', 'Hearts', 'Spades');
$cards = array('Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King');

$deck = pc_array_shuffle(range(0, 51));

while (($draw = array_pop($deck)) != NULL) {
    print  $cards[$draw / 4] . ' of ' . $suits[$draw % 4] . "\n";
}

This code uses the pc_array_shuffle( ) function from Recipe 4.21.

Discussion

Here, a pair of arrays, $suits and $cards, is created to hold the English representation of a card. The numbers 0 through 51 are randomly arranged and assigned to $deck. To deal a card, just pop them off the top of the array, treating the array like a literal deck of cards.

It’s necessary to add the check against NULL inside the while, otherwise the loop terminates when you draw the zeroth card. If you modify the deck to contain the numbers 1 through 52, the mathematics of deciding which number belongs to which card becomes more complex.

To deal multiple cards at once, call array_slice( ):

array_slice($deck, $cards * -1);

See Also

Recipe 4.21 for a function that randomizes an array; documentation on array_slice( ) at http://www.php.net/array-slice.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata