【问题标题】:Ternary IF causes out of memory三进制 IF 导致内存不足
【发布时间】:2012-05-16 08:29:24
【问题描述】:

我遇到了一些奇怪的事情。我试图使用以下三元 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['creditUsed'] > $row['creditLimit'] ? 'color:red;' : '') ;

没关系。

对不起!

【问题讨论】:

    标签: php memory-leaks ternary-operator


    【解决方案1】:

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

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

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

    【讨论】:

    • 按照您的回答进行了编辑。不过会接受你的答案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 2013-08-02
    • 2012-12-15
    • 1970-01-01
    相关资源
    最近更新 更多