I have a simple card game (using 52 cards – no jokers) that I want to randomly pick 1 card at a time until the winning card is chosen.
I have the following array:
$cards = array(
'diamond' => array(
'A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'
),
'heart' => array(
'A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'
),
'club' => array(
'A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'
),
'spades' => array(
'A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'
),
);
As you can see, this array is sorted. I would like to shuffle them using the PHP function shuffle($cards); but it didn’t work.
What can I do in order to get this suffled?
I’d make classes
DeckandCard. Card would hold what suit it is, as well as its ‘number’. Then you can call methodshuffleonDeck, which is simply an array of Cards. This way, all of the cards are sorted independent of their suit.[Update] Features:
__constructandreset. They now use a new function,createDeck, which usescreateSuitto ease the creation process.jsonSerializewill return the data to be serialized. In PHP 5.4 and above you can calljson_encodeon the object if it implements this interface. Before then, you can calljson_encode($deck->jsonSerialize()).count($deck)to get the size of the deck.deck[0]->suitwould return the suit of the first card of the deck.foreachloop.