Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable assignment into if statement for example

I'm a bit confused about operator precedence actually.

Here is an example that doesn't match with the php official website

 function getValue($key) {
      $array = ['un' => 1, 'six' => 6];

      if (array_key_exists($key, $array)) {
           return $array[$key];
      }

      return null;
 }

 var_dump(null === $t1=getValue('un'));
 var_dump(null === $t2=getValue('blablablaaaaaa'));
 // And now I switch
 var_dump($t3=getValue('un') ===  null);
 var_dump($t4=getValue('blablablaaaaaa') === null);

OUTPUT

 bool(false)
 bool(true)
 // After the switch
 bool(false)
 bool(true)

This is not what I was expecting for the two first outputs, because the comparison is higher-precedence than assignment. So php should've tried to compare null === $t1, or $t1 has not been declared yet, so a warning or error or whatever should've been raised. Or that didn't happen. Do you notice that PHP sometimes treat assignment before comparison although comparison is higher-precedence and thus should always be performed before assignment?. Any explanations about this?

My second question is: should this be avoided by always splitting up this kind of expression?

UPDATE

N.B

 var_dump($t1, $t2, $t3, $t4); 
 // OUTPUT

 int(1)
 NULL
 // After the switch
 bool(false)
 bool(true)
like image 562
smarber Avatar asked Mar 16 '26 04:03

smarber


1 Answers

=== is non-associative.

Non-associative operators are operators that have no defined behavior when used in sequence in an expression.

And in docs

= has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.

So it can be assumed PHP (in any of the expression) will first assign the return value of the function to the variable and then compare.

like image 133
Sougata Bose Avatar answered Mar 18 '26 20:03

Sougata Bose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!