Page 1 of 1

Associative Arrays

Posted: Sun Sep 25, 2011 5:49 am
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>";}	
?>

Re: Associative Arrays

Posted: Sun Sep 25, 2011 6:26 am
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.

Re: Associative Arrays

Posted: Sun Sep 25, 2011 11:43 pm
by indyjoel
Many thanks. It worked exactly as you said and I can better understand how these arrays works

Re: Associative Arrays

Posted: Mon Sep 26, 2011 6:28 pm
by Eric!
No problem. I also learned something new. I haven't seen the "shuffle" function before now.