DemCodeLines
DemCodeLines

Reputation: 1920

Get win/loss streak from an array in PHP

With the following code, I analyze all the games that a team has played yet and create an array with the results:

public function getResults($id) {
    $array = array();
    $scores = $this -> getAvailableScoresForTeam($id);
    for ($i = 0; $i < count($scores); $i++) {
        $homeTeam = $scores[$i]['homeTeam'];
        $awayTeam = $scores[$i]['awayTeam'];
        $homeScore = $scores[$i]['homeScore'];
        $awayScore = $scores[$i]['awayScore'];

        if ($homeTeam == $id && $homeScore > $awayScore) {
            $array[$i] = "W";
        }
        elseif ($awayTeam == $id && $awayScore > $homeScore) {
            $array[$i] = "W";
        }
        elseif ($homeTeam == $id && $homeScore < $awayScore) {
            $array[$i] = "L";
        }
        elseif ($awayTeam == $id && $awayScore < $homeScore) {
            $array[$i] = "L";
        }
    }
    return $array;
}

For example, if the team 1 played 4 total games, lost the first one and won the last 3, then the array for team 1 would be: (L, W, W, W)

What I am having trouble with is determining the win/loss streak. With the array above, I need to analyze the last couple of elements and see if they were losses ("L") or wins ("W") and if so, then how many.

For the output, I am only trying to get the most recent one. So for (L, W, W, L, W, W), it should be 2 wins since the last two games were won and the one before that wasn't.

Upvotes: 2

Views: 757

Answers (1)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174997

$arr = ["W", "L", "W", "W"];     //Definition
$arr = array_reverse($arr);      //Reverse the array.
$last = array_shift($arr);       //Shift takes out the first element, but we reversed it, so it's last.  
$counter = 1;                    //Current streak;
foreach ($arr as $result) {      //Iterate the array (backwords, since reversed)
    if ($result != $last) break; //If streak breaks, break out of the loop
    $counter++;                  //Won't be reached if broken
}

echo $counter;                   //Current streak.

Upvotes: 6

Related Questions