Associative Arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
indyjoel
Forum Newbie
Posts: 2
Joined: Sun Sep 25, 2011 5:25 am

Associative Arrays

Post by indyjoel »

Hi need some help on the code
I can put data into the associate array but I cannot print the value with foreach ($dealer as $dc=> $dcv){echo "The Dealer card is :" . $dc ($dcv) . "<br>";}

Any help for a dummy would be appreciated.

Code: Select all

<?php
$suits = array ("Spades", "Hearts", "Clubs", "Diamonds");
$faces = array ("Two", "Three", "Four", "Five", "Six", "Seven", "Eight",  "Nine", "Ten", "Jack", "Queen", "King", "Ace");
$deck = array();
foreach ($suits as $suit) {
    foreach ($faces as $face) {$deck[] = array ("face"=>$face, "suit"=>$suit);}
}
shuffle($deck);
$dealer = array();
$card = array_shift($deck);
array_push ($dealer, $card);
$card = array_shift($deck);
array_push ($dealer, $card);
foreach ($dealer as $dc=> $dcv){echo "The Dealer card is :" . $dc ($dcv) . "<br>";}	
?>
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: Associative Arrays

Post by Eric! »

[text]array(2) { [0]=> array(2)
{ ["face"]=> string(5) "Queen"
["suit"]=> string(5) "Clubs" }
[1]=> array(2) {
["face"]=> string(3) "Two"
["suit"]=> string(8) "Diamonds" }
} [/text]
Your $dealer is an array of arrays with 2 cards because you are calling array_push twice.
$dealer[0]["face"]="Queen" and $dealer[1]["face"]="Two".

Also your echo statement is a little off. Try

Code: Select all

foreach ($dealer[0] as $dc=> $dcv){echo "The Dealer card is: " . $dc ." (".$dcv.")<br>";}
I put $dealer[0] in there so it would work with your code as written, but you'll probably want to fix the code so the dealer only has one card. Or if you want your dealer to have more than one card:

Code: Select all

foreach ($dealer as $dealer_cards) {
    foreach ($dealer_cards as $dc => $dcv) {
        echo "The Dealer card is: " . $dc . " (" . $dcv . ")<br>";
    }
}
By the way, you might want to unset the dealer's card from the deck, otherwise you'll have duplicate cards running around and some very suspicious poker players.... Since you're shifting right off the top of the deck, just use unset($deck[0]); after every card drawn.
indyjoel
Forum Newbie
Posts: 2
Joined: Sun Sep 25, 2011 5:25 am

Re: Associative Arrays

Post by indyjoel »

Many thanks. It worked exactly as you said and I can better understand how these arrays works
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: Associative Arrays

Post by Eric! »

No problem. I also learned something new. I haven't seen the "shuffle" function before now.
Post Reply