Forum Moderators: coopster

Message Too Old, No Replies

Counting items in an array having X attribute

Apparently, I can only count to 1

         

riverstyx

1:18 am on Dec 31, 2006 (gmt 0)

10+ Year Member



Hi, folks -

I could use some insight into solving what should be an easy task. Example:

I want to randomly select 5 cards from a standard playing card deck and count how many of each suit are returned:

[connect]
$sql = "SELECT * FROM cards ORDER BY RAND()LIMIT 5";
$result = mysql_query($sql);
while($cards = mysql_fetch_array($result)) {

$value = $cards["card_value"];
$suit = $cards["card_suit"];
$image = $cards["card_image"];
--------

Using count() within the loop returns a count of 1 since each card can only be of one suit. I tried using something like this:

$spades = 0;
if($suit='spades') {
$spades = $spades+1;
}

and I tried a foreach statement to count within the loop which always returns a count of 1.

Would someone be so kind as to point me in the right direction?

RS

bomburmusicmallet

1:37 am on Dec 31, 2006 (gmt 0)

10+ Year Member



Not sure if your code is cut-n-paste, but if it is, this is incorrect:

if($suit='spades') {
$spades = $spades+1;
}

It should be:

if($suit=='spades')

Notice the double equal sign.

riverstyx

3:58 pm on Dec 31, 2006 (gmt 0)

10+ Year Member



Well, that did help a lot. I did this within the loop:

if($card_suit == 'spades') {
$spades=$spades+1;
}
if($card_suit == 'hearts') {
$hearts=$hearts+1;
}
if($card_suit == 'clubs') {
$clubs=$clubs+1;
}
if($card_suit == 'diamonds') {
$diamonds=$diamonds+1;
}
and then printed the counts outside the loop and everything is being counted correctly now. Thanks...

IanKelley

9:57 am on Jan 2, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



It's good to program efficiently right from the start.

That said, your loop will test every if statement even though only one of them can be true. Replace the last 3 if's with elseif or use continue instead.

coopster

4:34 pm on Jan 2, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



True. A switch [php.net] control structure would work well too.

whoisgregg

8:57 pm on Jan 2, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



So long as you can trust the $card_suit variable, you could use variable variables [php.net].

${$card_suit}++;