0

I have a rudimentary understanding of both operators, but would like to know what the subtle differences are between the two which might cause "hard-to-track" bugs.

farinspace
  • 7,811
  • 6
  • 32
  • 44
  • 2
    You can find the documentation at php.net, which would allow you to ask more specific questions. – Ulrich Eckhardt Nov 10 '21 at 18:09
  • 4
    Does this answer your question? [PHP ternary operator vs null coalescing operator](https://stackoverflow.com/questions/34571330/php-ternary-operator-vs-null-coalescing-operator) – eglease Nov 10 '21 at 18:16

1 Answers1

0

The ?: is just a shortcut of the Ternary Operator expression ? if true : if false, whereas the Null Coalescing Operator ?? only has that construct and tests for whether the variable is set/defined or not null.

$a = '';
echo $a ?: 'test ?:';
echo $a ?? 'test ??';

Yields test ?: because $a is an empty string that evaluates to false but it is set.

//$a = null;
echo $a ?: 'test ?:';
echo $a ?? 'test ??';

Yields:

Warning: Undefined variable $a test ?: test ??

In the first line because $a is not set which generates a notice/warning and evaluates to false and in the second line because it is not set.

In short:

  • ?: evaluates the expression to true or false and executes if false.
  • ?? executes if the expression is not null
AbraCadaver
  • 77,023
  • 7
  • 60
  • 83