Newb lost in a nested loop

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
xpeeblix
Forum Newbie
Posts: 2
Joined: Mon May 11, 2009 10:25 pm

Newb lost in a nested loop

Post by xpeeblix »

I'm starting out learning PHP and find myself stuck in a function to create a deck of cards.

What I want to end up with is an associative array with a suit/card key like Queen4 or Q4 and a numeric value for the card, so Q4=>4, K8=>8 and so on. I should add that aces are 1 and Jack, Queen, King are 11,12 and 13.

I need to do it for every suit, and I'm attempting to do it with nested foreach loops.

Here's what I have:
=============================================================

Code: Select all

 
function getDeck(){
    $deck = array();
    $card = range(1,13);
    $suit = array(C,D,H,S);
    $value = array(1,2,3,4,5,6,7,8,9,10,10,10,10);
    foreach($suit as $var1){
        foreach($card as $var2){
            foreach($value as $var3){
                $deck[$var1.$var2] = $var3;
            }
        }
    }
    print_r ($deck);
}
 
 
======================================================
This, unfortunately, only puts the last value of $var3 in the array which otherwise works.

Can someone help me out?
Last edited by Benjamin on Mon May 11, 2009 11:38 pm, edited 1 time in total.
Reason: Added [code=php] tags.
User avatar
susrisha
Forum Contributor
Posts: 439
Joined: Thu Aug 07, 2008 11:43 pm
Location: Hyderabad India

Re: Newb lost in a nested loop

Post by susrisha »

Code: Select all

 
unction getDeck(){
$deck = array();
$card = range(1,13);
$suit = array(C,D,H,S);
$value = array(1,2,3,4,5,6,7,8,9,10,10,10,10);
foreach($suit as $var1){
foreach($card as $var2){
foreach($value as $var3){ //here is your problem.. the loop executes and assigns the last value to the variable
$deck[$var1.$var2] = $var3;
}
}
}
print_r ($deck);
}
 
I have modified the code for your correct output. the code looks like this

Code: Select all

 
function getDeck(){
$deck = array();
$card = range(1,13);
$suit = array('C','D','H','S');
$value = array(1,2,3,4,5,6,7,8,9,10,10,10,10);
foreach($suit as $var1){
foreach($card as $var2){
 
$deck[$var1.$var2] = $value[$var2-1]; // take the value from the value array directly
 
}
}
print_r ($deck);
}
getDeck();
 
hope that helps
xpeeblix
Forum Newbie
Posts: 2
Joined: Mon May 11, 2009 10:25 pm

Re: Newb lost in a nested loop

Post by xpeeblix »

susrisha wrote: hope that helps
Yes! Perfect!

Thanks, that's really quite clever. I'm proud to say that I *did* realize that $var3 was running through and only putting the last value in the array, but got so focused on solving this with a nested foreach loop that I wasn't considering other options.

Thank you, thank you, thank you!
Post Reply