Sunday, February 5, 2012

PHP Increment Operator Bug? ... Nope!

So this is one of those things that I ran into recently that I never knew, that I probably should have.

First the problem. I was working on a project and had a snippet of code similar to this:
$a_counter = has_some_setting(); foreach ($arr as $key => $val) { if ($val == $some_condition) { $a_counter++; } } echo $a_counter;
I was expecting the output to be greater than 1, but for some reason it was always 1. To debug, I adjusted the code to see that my value should be being incremented.
$a_counter = has_some_setting(); foreach ($arr as $key => $val) { if ($val == $some_condition) { echo $val . ' == ' . $some_condition . '
'; $a_counter++; } } echo $a_counter;

Indeed it was, so why was $a_counter++ not working? Changing it to $a_counter += 1; worked fine.

At first I thought it was a PHP bug, and after doing a Google search, found a PHP Increment/Decrement bug report. Lo and behold, that is exactly what my problem was. My has_some_setting() function returns a BOOLEAN, not an INTEGER. And according to the PHP docs, this is not a bug.
Note: The increment/decrement operators do not affect boolean values. Decrementing NULL values has no effect too, but incrementing them results in 1.

So, the long and short of it is, if your increment/decrement operators aren't returning values you expect, make sure your variable is not a boolean. Also, it may be worth reviewing the Increment/Decrement operators on strings example.

No comments: