Why am I getting a division by zero error here?

I'm getting a division by zero error on this line of code:

$ratio['p{W}'] = ($ratio['{W}'] === 0) ? 0 : ($colorTotal === 0) ? 0 : ($ratio['{W}'] / $colorTotal) * 100;

I've tested the above with:

echo '$ratio[{W}]:'.$ratio['{W}'].', $colorTotal:'.$colorTotal;

if($ratio['{W}'] === 0) {
    echo('$ratio[{W}]: zero');
}
else {
    echo('$ratio[{W}]: not zero');
}

if($colorTotal === 0) {
    echo('$colorTotal: zero');
}
else {
    echo('$colorTotal: not zero');
}

and the results are:

[01-Jul-2015 17:40:26 UTC] $ratio[{W}]:0, $colorTotal:0

[01-Jul-2015 17:40:26 UTC] $ratio[{W}]: zero

[01-Jul-2015 17:40:26 UTC] $colorTotal: zero

It seems I should never reach this point ( $ratio['{W}'] / $colorTotal ) in the code since the previous criteria is 0 in the checks but it seems to reach it? How can I prevent this error?


Ternary operators are left-associative in PHP. Your code is equivalent to:

$ratio['p{W}'] = (($ratio['{W}'] === 0) ? 0 : ($colorTotal === 0)) ? 0 : ($ratio['{W}'] / $colorTotal) * 100;

meaning that ($ratio['{W}'] === 0) ? 0 : ($colorTotal === 0) ($ratio['{W}'] === 0) ? 0 : ($colorTotal === 0) evaluates first. The result of this is either 0 or true , meaning that the true part of the second ternary will always execute.

It looks to me like you probably want to make the whole expression right-associative:

$ratio['p{W}'] = ($ratio['{W}'] === 0) ? 0 : (($colorTotal === 0) ? 0 : ($ratio['{W}'] / $colorTotal) * 100);

I'll start out by adding parenthesis around your ternaries, since I'm afraid ElGavilan is right. Your one-liner is quite ugly to read, and refers to code we don't have, which means we can't test your code.

I like ternaries... but not that way !


$ratio['p{W}'] = ($ratio['{W}'] === 0) ? 0 : ($colorTotal === 0) ? 0 : ($ratio['{W}'] / $colorTotal) * 100;

($ratio['{W}'] === 0)表示$ratio['{W}']为false,则在这两种情况下执行错误代码($colorTotal === 0) ($ratio['{W}'] === 0) & ($colorTotal === 0)值变为0.对于最后一种情况分割情况0/0也是如此。

链接地址: http://www.djcxy.com/p/69368.html

上一篇: PHP:使用同名方法处理特征

下一篇: 为什么我在这里通过零错误得到一个分区?