phploopsforeachalternate

What is a cleaner way to alternate colors in a foreach loop in PHP and when would processing speed really be a factor?


Although this works, speed and cleanliness matter.

if (file_exists($fileToCheck)) {
    $contents = file_get_contents($fileToCheck);
    $lines = array_reverse(explode("\n", trim($contents))); 
    $line ="";
    $c = 0;
    foreach($lines as $row) {
        if ($c == 0) { $line .= "<span style='color:red;font-size:10px;'>".$row."</span><br>"; $c = +2; }
        if ($c == 1) { $line .= "<span style='color:blue;font-size:10px;'>".$row."</span><br>"; $c = +2; }
        if ($c == 2) { $c = 1; }
        if ($c == 3) { $c = 0; }
    }
} else { $line = "Huzzah! No errors today!"; }

Thanks.


Solution

  • You want to use the modulus/modulo operator.

    So, if you wanted to make all even numbers red, and the others blue, you would do this:

    foreach($lines as $row) {
        if ($c % 2 == 0) { 
            $line .= "<span style='color:red;font-size:10px;'>".$row."</span><br>"; 
        } else {
            $line .= "<span style='color:blue;font-size:10px;'>".$row."</span><br>"; 
        }
        $c++;
    }
    

    You could simplify this further:

    foreach($lines as $row) {
        $colour = ($c % 2 == 0) ? 'red' : 'blue';
        $line .= "<span style='color:".$colour.";font-size:10px;'>".$row."</span><br>"; 
        $c++;
    }
    

    https://www.php.net/manual/en/language.operators.arithmetic.php