jared_flack
jared_flack

Reputation: 1646

PHP variable assignment needs parentheses

I wrote some code and found it didn't work as I expected.

For example, the following would return false or throw an exception, Undefined variable: a:

if ($a = 12 && $a == 12) {
    return true;
} else {
    return false;
}

I fixed it by wrapping the assignment in parentheses:

if (($a = 12) && $a == 12) {
    return true;
} else {
    return false;
}

It was just a lucky guess. I'm wondering why the parentheses are needed and I haven't found anything that explains why.

Upvotes: 1

Views: 146

Answers (1)

merlin2011
merlin2011

Reputation: 75575

That is because of operator precedence. The assignment operator = has a lower precedence than &&, so without the parenthesis you are effectively doing the following.

if ($a = (12 && $a == 12))

Observe that the second $a is not yet defined before the assignment happens, because it has to be evaluated before the assignment can happen.

Upvotes: 7

Related Questions