Skip to content

Instantly share code, notes, and snippets.

@dsposito dsposito/Cards.php
Last active Jan 6, 2018

Embed
What would you like to do?
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));
@JakePrice86

This comment has been minimized.

Copy link

commented Aug 26, 2015

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

This comment has been minimized.

Copy link

commented Oct 22, 2016

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
You can’t perform that action at this time.