0

I tried out this code:

<?php
    if(isset($a) && ($a ==4)) echo "$a ==4";
?>

and I was surprised that I did not get an error, because $a is not defined. I thought one needs to write

<?php
    if(isset($a))
        if($a == 4) echo "$a == 4";
?>

Why is the first version not throwing an error if I check isset($a) and ($a ==4) simultaneously? Is there any disadvantage when using the short code if(isset($a) && ($a ==4))? I do not trust it, but it becomes really handy when an else branch is needed.

Adam
  • 25,960
  • 22
  • 158
  • 247
  • 5
    and stops on first false – splash58 May 09 '16 at 11:19
  • This is a [good answer](http://stackoverflow.com/a/2535578/2233391) to your question. – Henders May 09 '16 at 11:22
  • 3
    It's called "lazy evaluation".... Conditions aren't checked simultaneously, but one at a time in order from left to right: if any of a series of ANDed criteria is false, then PHP doesn't bother wasting any time checking the subsequent criteria, because it doesn't matter what they are, the final result will always be false – Mark Baker May 09 '16 at 11:22

2 Answers2

7

PHP checks your if condition from left to right. isset() returns false so it doesn't check for ($a == 4) it aborts the if and continues the script.

If we do it the other way around:

if(($a ==4) && isset($a)) echo "$a ==4";

This will return an undefined notice.

Daan
  • 12,099
  • 6
  • 34
  • 51
4

That has to do with the && operator.

What it does is check the first operator first: if it is false, then it quits the condition right there, without evaluating the second condition because the entire condition is already false. Therefore, the second condition never throws an error because it is not evaluated.

This is in contrast to the & operator, which evaluates both expressions first and would create an error.

See this SO post for the difference between the two.

Community
  • 1
  • 1
Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94