三元 IF 导致内存不足


Ternary IF causes out of memory

我遇到了一些奇怪的东西。我试图使用以下三元 if 语句:

$output .= ($row['creditUsed'] > $row['creditLimit'] ? 'color:red;' : $output) ;

这导致我的浏览器挂起,最终导致PHP内存不足错误。

现在我只是使用:

if($row['creditUsed'] > $row['creditLimit'])
{
    $output .= 'color:red;' ;
}

哪个工作正常。

有谁知道为什么会这样?if 语句处于 while 循环中,完整的代码太多了,无法发布:

$i = 0 ;
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
if($i == 0)
{
    //something
}
if($row['amountDue'] > $row['amount'] && $row['amount'] > 0.01)
{
// Stuff
}
else
{
    $output .= ($row['creditUsed'] > $row['creditLimit'] ? 'color:red;' : $output) ;
}
$i++ ;
}

是我的错!我意识到$output在循环的每次迭代中都呈指数级增长。我把它改成:$output .= ($row['信用已使用']> $row['信用限制'] ?"颜色:红色;" : "( ;

而且没关系。

不好意思!

您反复将$output附加到自身(如果条件失败(,导致它在每次迭代时大小翻倍(即指数增长(。

如果这里真的必须使用三元运算符,则需要在第三个操作数中附加一个字符串,而不是原始字符串:

$output .= ($row['creditUsed'] > $row['creditLimit'] ? 'color:red;' : '');