在 PHP 中的 foreach 循环中交替颜色的更简洁方法是什么?处理速度何时真正成为一个因素?

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

虽然这可行,但速度和清洁度很重要。

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!"; }

谢谢。

您想使用 modulus/modulo 运算符。

所以,如果你想让所有的偶数都变成红色,而其他的变成蓝色,你可以这样做:

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++;
}

您可以进一步简化:

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

是这样的吗?相同的想法只是更少的代码

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