PHP’s && has higher precedence than =

Translation: the operands of a logical && operator (not to be confused with the similar but infrequently used and operator) get evaluated before the operands of an assignment = operator (see operator precedence for more).

In PHP people frequently use the evaluation step of an if or while control structure to assign a value and then perform some action on that value, provided it evaluates to true, e.g.

if ($return_value = some_function()) {
  // do something with $return_value
}

However, should you be tempted to both test whether the returned value is true and whether another flag is set (as I was today), make sure to not do this (as I did):

if ($return_value = some_function() && $flag == 'some value') {
  // do something with $return_value
}

…because some_function() && $flag == 'some value' will get evaluated first and then the boolean result of that will get assigned to $return_value, instead of the intended return value of some_function().

This problem is easily solved with parentheses:

if (($return_value = some_function()) && $flag == 'some value') {
  // do something with $return_value
}

Lesson learned.

relatedposts

post a comment

name
blog (optional)
comment