Marc.2377 Marc.2377 -4 years ago 69
PHP Question

Addition assignment won't assign inside conditional

It is my (intuitive) understanding that using the addition assignment operator

+=
in PHP for variables of the integer type would yield the result of the addition, while incrementing the left-side operand by the value of the right-side operand at the same time.

This understanding appears to be wrong, hence my question. Considering the following snippet of code:

$itr = 10;
$incr = 10;

if ($itr += $incr > 10) { // evaluates as true...
echo $itr; // but value of $itr remains unchanged
}


Why does it output 10 instead of 20?

The same happens using the ternary form:

echo ($itr += $incr > 10) ? $itr : 'neverhere'; // prints 10
// Note: I know that parentheses aren't really necessary here, it's just a personal practice.


What is going on?




Edit: Well, I found out that surrounding the expression
$itr += $incr
with parentheses fixes the apparent problem. Still, a proper explanation of why would be very cool. My appreciation in advance.

Answer Source

Operator precedence: The > is evaluated first and leads to false. When casted to an integer to add to your value, false is casted to 0.

So:

$itr += $incr > 10

becomes:

$itr += ($incr > 10)
$itr += (false)
$itr += 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download