phpnull-coalescing-operator

Can I use `??` (Null coalescing operator) instead of empty?


I have lots of code like this

$Var = !empty($Data->title) ? ' string1 ' . $Data->title : ' string2 ' . $Var2;

I searched on the web and I found ?? (Null coalescing operator)

Because of that, I assume can do something like this

$Var = ' string1 ' . $Data->title ?? ' string2 ' . $Var2;

I asked that because I know ?? is used for isset() or NULL but I need empty() for my project code.


Solution

  • As you already said

    $a ?? $b
    

    is a short hand for (isset($a)) ? $a : $b;

    But the function isset() returns false if a variable was not defined, or if it was defined as null. Whereas !empty() returns FALSE if var was not defined or has a empty or non-zero value. So you can't use ?? for !empty().

    You could use

    $a ?: $b 
    

    which is a shorthand for

    ((bool)$a) ? $a : $b;
    

    Here are the rules how a variable is casted to a Boolean.

    In short ((bool)$a) == (!empty($a)) is always true, except if $a is a SimpleXML object created from empty tags.

    However, in your case, neither ?: nor ?? will work, because ' string1 ' . $Data->title is always non-empty and defined.