galvin Posted January 16, 2009 Share Posted January 16, 2009 I have 12 variables ($1rank, $2rank, $3rank all the way through $12rank) being created and each one will always be equal to one of two numbers. So if the two numbers end up being 3 and 7, then out of those 12 variables, there could be eight 3s and four 7s, or two 3s and ten 7s, etc. What is the best way to get the sum total of each number? For example, if the variables were... $1rank = 3 $2rank = 7 $3rank = 7 $4rank = 7 $5rank = 7 $6rank = 3 $7rank = 7 $8rank = 3 $9rank = 7 $10rank = 7 $11rank = 7 $12rank = 3 ..what PHP code could I use to look at all 12 variables and give a TOTAL COUNT of the 3s (which in this case would be 4) and a TOTAL COUNT of the 7s (which in this case would be . Any ideas? Quote Link to comment https://forums.phpfreaks.com/topic/141029-solved-getting-total-count-of-two-variables/ Share on other sites More sharing options...
machupicchu Posted January 16, 2009 Share Posted January 16, 2009 you should use an array for rank, and use a for loop to calculate how many 3's and 7's there are. $rank = array(3, 7, 7, 7); $rank[4] = 7; // user either way to assign values to the array // then to count 3's and 7's use a loop $size = sizeof($rank); $threes = 0; $sevens = 0; for ($i = 0; $i < $size; $i++) { if ($rank[$i] == 3) $threes++; // add 1 to $threes if ($rank[$i] == 7) $threes++; // add 1 to $sevens } echo "Threes = $threes and Sevens = $sevens"; Quote Link to comment https://forums.phpfreaks.com/topic/141029-solved-getting-total-count-of-two-variables/#findComment-738149 Share on other sites More sharing options...
galvin Posted January 16, 2009 Author Share Posted January 16, 2009 Excellent, that'll do what I need! Thanks a lot!! Quote Link to comment https://forums.phpfreaks.com/topic/141029-solved-getting-total-count-of-two-variables/#findComment-738156 Share on other sites More sharing options...
sasa Posted January 16, 2009 Share Posted January 16, 2009 or you can use <?php $rank = array(3,7,7,7,7,3,7,3,7,7,7,3); print_r(array_count_values($rank)); ?> Quote Link to comment https://forums.phpfreaks.com/topic/141029-solved-getting-total-count-of-two-variables/#findComment-738159 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.