Skip to content

Instantly share code, notes, and snippets.

@dsposito
Last active April 23, 2021 14:44
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsposito/6679592 to your computer and use it in GitHub Desktop.
Save dsposito/6679592 to your computer and use it in GitHub Desktop.
A simple class for interacting with a deck of cards.
<?php
/**
* Contains methods for interacting with a deck of cards.
*
* @author Daniel Sposito <daniel.g.sposito@gmail.com>
*/
class Deck
{
/**
* Builds a deck of cards.
*
* @return array
*/
public static function cards()
{
$values = array('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A');
$suits = array('S', 'H', 'D', 'C');
$cards = array();
foreach ($suits as $suit) {
foreach ($values as $value) {
$cards[] = $value . $suit;
}
}
return $cards;
}
/**
* Shuffles an array of cards.
*
* @param array $cards The array of cards to shuffle.
*
* @return array
*/
public static function shuffle(array $cards)
{
$total_cards = count($cards);
foreach ($cards as $index => $card) {
// Pick a random second card.
$card2_index = mt_rand(1, $total_cards) - 1;
$card2 = $cards[$card2_index];
// Swap the positions of the two cards.
$cards[$index] = $card2;
$cards[$card2_index] = $card;
}
return $cards;
}
}
$cards = Deck::cards();
echo "Cards: " . implode(', ', $cards);
echo "<br /><br />Shuffled Cards: " . implode(', ', Deck::shuffle($cards));
@jakeydevs
Copy link

There is an issue with the shuffle function duplicating the first card - might be best to replace that function with a less random shuffle function.

@henrisson
Copy link

I think it's because of the for foreach loop on a changing array.
This seems to work
for($index=0;$index<count($cards);$index++) { $card = $cards[$index]; ......... }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment