user1234 user1234 - 2 months ago 7
PHP Question

Php OR operator gives wrong result?

I am surprised with the output of

OR
operator in
php


$a = 5;

echo $b = ((intval($a) == 8 || 2) && intval($a) != 0 ? $a : NULL);


It echo 5 but i expect
NULL

Answer

As you stated, your $a is not 8 or 2. So assume it's 5.

How your evaluation works:

((intval($a) == 8 || 2) && intval($a) != 0 ? $a : NULL);

  1. Compare intval($a) == 8.
  2. No matter what you get from #1, do || 2 which leads to true (non-zero number is loosely equals true)
  3. Compare intval($a) != 0 - leads to true.
  4. Compare true && true => true
  5. Answer is $a.

Step-by-step:

 (intval($a) == 8 || 2) && intval($a) != 0 ? $a : NULL;
 (false || 2) && intval($a) != 0 ? $a : NULL);
 (false || true) && intval($a) != 0 ? $a : NULL;
 true && intval($a) != 0 ? $a : NULL;
 true && true ? $a : NULL;
 $a;

TL;DR

To get NULL, change || 2 to || intval($a) == 2