Home > other >  Checking if variable exist and if it has a certain value in one line
Checking if variable exist and if it has a certain value in one line

Time:02-16

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;

CodePudding user response:

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) { }
  • Related