Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

This example shows us the differences between ternary x ? x : z (x ?: z) and null coalescing operators x ?? z in PHP.


Example


$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