Areza
Areza

Reputation: 721

PHP7: how to use question marks(?? operator) for empty variable

Please Check this code:

$title1 = null; // maybe isset or not
$title2 = 'title2'; // maybe isset or not
$title3 = null; // maybe isset or not

$title = $title1 ?? $title2 ?? $title3;

I want print value of non-empty variable.

in this example, with

echo $title; 

I want it print value of $title2 But it print $title1 value.

I can do it with switch of if, But can I do it with ?? method?

if(isset($title1) && $title1)
  $title = $title1;
elseif(isset($title2) && $title2)
  $title = $title2;
elseif(isset($title3) && $title3)
  $title = $title3;

Upvotes: 0

Views: 646

Answers (1)

Pinke Helga
Pinke Helga

Reputation: 6702

Your code is definitely correct and should work as expected, outputting 'title2'.

However, your condition isset($title1) && $title1 is not the same. This is more like the 'Elvis' operarator ?: checking for evaluation to boolean, except that the Elvis operator always returns a value (that might be null) and throws a notice on undefined operands. You would have to mute that by the @ operator.

Your if-else-construct is almost equivalent to

$title = @$title1 ?: @$title2 ?: @$title3;

The only difference is that $title here is assigned anyway while in your if-else-construct $title is left untouched when all operands are evaluated to false.

Be aware that muting by the @ operator also prevents critical errors to be shown, e.g. when using a function as operand.

An alternative is to define your own function. Arguments by value throw a notice on unset variables as well, however, arguments by reference do not. You can design a variadic function taking references:

function firstNonEmpty(&...$variableRefs)
{
  $v = null;         // ensure declaration since loop might not interate at all
  foreach ($variableRefs as $v)
    if($v) break;
  return $v ?: null; // we want null even if last value is like false
}

$c = 'value not considered to be empty';
$v = firstNonEmpty($a, $b, $c, $d);

Arguments by reference do not accept literals, thus appending some as default argument will not work. However, you can simply use the null-coalescing operator ?? in this case. There is fairly no use-case to add more than one default literal since you know at developtment time whether or not a literal evalualtes to false.

$v = firstNonEmpty($a, $b, $c, $d, 'default')  ; // does NOT work
$v = firstNonEmpty($a, $b, $c, $d) ?? 'default'; // DOES work

// One strange thing of PHP is that
$v = firstNonEmpty($a, ...[0, null, '', 'non-empty']); // DOES work as well

The latter literally creates an array of literals on the fly and references the destructed items. The only thinkable use-case having more than one literal would be generated code by eval.

Upvotes: 1

Related Questions