user1234 - 10 months ago 43

PHP Question

I am surprised with the output of

`OR`

`php`

`$a = 5;`

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

It echo 5 but i expect

`NULL`

Answer Source

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);`

- Compare
`intval($a) == 8`

. - No matter what you get from #1, do
`|| 2`

which leads to`true`

(non-zero number is loosely equals`true`

) - Compare
`intval($a) != 0`

- leads to true. - Compare
`true && true`

=>`true`

- 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`