tags:

views:

39

answers:

4

I have an array:

$record = array(Won,Lost,Won,Won,Lost);

I want to count the number of wins and losses in the array.

So everytime it finds "Won" in the array, do a $won++, and the same for loss, $loss++

I want to print out the record after that is completed.

print $won.' - '.$lost;

I think I figured it out, revisions to make this more efficient, will be appreciated.

<?php
$won = 0;
$lost = 0;

foreach ($record as $i => $value) {
  if($value == "Won") {
    $won++;
  } elseif($value == "Lost") {
    $lost++;
  }
}?>
+2  A: 

Are they constants, or did you forget to quote literal strings? I'm going to assume they are string literals.

Anyway, you could do

$won = $lost = 0;

foreach($record as $rec) {

    switch ($rec) {
        case 'Won':
            $won++;
            break;
        case 'Lost':
            $lost++;
            break;
    }

}
alex
That should be a colon between `$won++` and `$lost++`.
casablanca
@casablanca Yep, good catch :)
alex
returns 2 wins and 2 losses, when it should be 2 wins and 1 loss (ignore the array values I used in the question)
Brad
@Brad show the array you are iterating through please.
alex
@Alex Array ( [0] => Won [1] => Lost [2] => Not-Final [3] => Won )
Brad
@Brad You never mentioned there were others besides "Win" or "Loss". I'll make an edit to accommodate.
alex
@Alex, sorry about that, still seems to get the win, loss count wrong, should be 2-1, your function produces 2-0
Brad
@Alex, nevermind, case 'Loss' should of been case 'Lost' - it worked, thanks!
Brad
@Brad That was a typo on my behalf. It should work now.
alex
+5  A: 

array_count_values() is what you're looking for

$counts = array_count_values($record);
zerkms
+1 for giving the right answer, even if it wasn't accepted
Mark Baker
+1  A: 

http://php.net/manual/en/function.array-walk.php set a callback, and you should be on your way

0x90
+1  A: 
<?php
$record = array('Won','Lost','Won','Won','Lost');
$won = 0;
$lost = 0;
foreach ($record as $stat) {
    switch($stat) {
        case 'Won':
                $won++;
                break;
        case 'Lost':
                $lost++;
                break;
    }
}
print $won.' - '.$lost;
?>
Ruel