1

I have always thought that if I want to check if a variable exists and has a certain value I have to use two if conditions:

if(isset($x)){
    if($x->age==5){}
}

But I realized its also possible to do it in one line this way:

if(isset($x) && ($x->age==5)){}

Can someone tell me why the second variation will not result in an error if $x is null. Given that $x is null and doesn't have the property age? Would it be trying to access a property that doesn't exist?

$x=null;
Syscall
  • 19,327
  • 10
  • 37
  • 52
Yeo Bryan
  • 331
  • 4
  • 24
  • 1
    Does this answer your question? [Does PHP have short-circuit evaluation?](https://stackoverflow.com/questions/5694733/does-php-have-short-circuit-evaluation) – CBroe Feb 16 '22 at 08:26

1 Answers1

4

Because $x is null, isset($x) is false. Then, because of the logical operator "AND" (&&), the condition cannot be fully validated, so, the test is stopped here and ($x->age==5) is not executed.

For a shorter code, as of PHP 8.0.1, you can use the NullSafe Operator (?->)

if ($x?->age == 5) { }
Syscall
  • 19,327
  • 10
  • 37
  • 52