Monday, 15 August 2016

php - 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?


Answer



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)
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);

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...