12/02/2018 - PHP
This example shows us the differences between ternary x ? x : z (x ?: z)
and null coalescing operators x ?? z
in PHP.
$a = 'A';
$b = 'B';
echo $a ? $a : $b; // A
echo $a ?: $b; // A
echo $a ?? $b; // A
-----------------------------------------------------------
$a = '';
$b = 'B';
echo $a ? $a : $b; // B
echo $a ?: $b; // B
echo $a ?? $b; // Returns empty value which is $a
-----------------------------------------------------------
$a = ' ';
$b = 'B';
echo $a ? $a : $b; // Returns empty value which is $a
echo $a ?: $b; // Returns empty value which is $a
echo $a ?? $b; // Returns empty value which is $a
-----------------------------------------------------------
$a = null;
$b = 'B';
echo $a ? $a : $b; // B
echo $a ?: $b; // B
echo $a ?? $b; // B
-----------------------------------------------------------
$a = false;
$b = 'B';
echo $a ? $a : $b; // B
echo $a ?: $b; // B
echo $a ?? $b; // 0/false
-----------------------------------------------------------
$a = true;
$b = 'B';
echo $a ? $a : $b; // 1/true
echo $a ?: $b; // 1/true
echo $a ?? $b; // 1/true
-----------------------------------------------------------
$b = 'B';
echo $a ? $a : $b; // PHP Notice: Undefined variable $a
echo $a ?: $b; // PHP Notice: Undefined variable $a
echo $a ?? $b; // B