PHP 8 interview question · Most asked

Compare `??`, `?:`, and `?->`.

Summary

?? returns the left operand unless it is null/undefined, ?: returns the left operand unless it is falsy, and ?-> safely calls a method or property on a possibly-null object.

Longer Answer

$a ?? $b doesn't emit a warning for undefined variables or keys, making it ideal for $_GET['x'] ?? 'default'. $a ?: $b treats 0, '', '0', [] and false as missing, which is often a bug for numeric input. ?-> chains through nulls. ??= (PHP 7.4) assigns only when null.

Key Points

  • ?? checks null/undefined only
  • ?: checks falsiness (beware 0 and '0')
  • ?-> short-circuits on null in chains
  • ??= assigns if null

Comparison / Tradeoffs

Operator Falls back when Example
?? null or undefined $_GET['page'] ?? 1
?: falsy $name ?: 'Anonymous'
?-> receiver is null $user?->profile

More most-asked PHP 8 questions

← All PHP 8 questions