Ternary Operator(?) vs Null coalescing operator(??) in PHP

Difference between Ternary operator and Null coalescing operator in PHP

Md. Abutaleb
Jan 12 · 1 min read

Ternary operator (?):

  1. Return false if the variable is empty
  2. Return false if the variable is null.
  3. Short form of use ?: like echo $a ?: ‘ Anything else’;
  4. You’ll get an error if the variable is not defined.

Null Coalescing Operator (??)

  1. Return true if the variable is defined even it is empty
  2. Return false if the variable is not defined. But won’t throw any undefined variable error.
  3. It’s working like ( !isset() || is_null() )
  4. It returns false if the variable is null

Example of Ternary Operator & Null Coalescing operator

$a = null;print $a ?? ‘b’; // b
print “\n”;
print $a ?: ‘b’; // b
print “\n”;
print $c ?? ‘a’; // a
print “\n”;
print $c ?: ‘a’; // Notice: Undefined variable
print “\n”;
$b = array(‘a’ => null);print $b[‘a’] ?? ‘d’; // d
print “\n”;
print $b[‘a’] ?: ‘d’; // d
print “\n”;
print $b[‘c’] ?? ‘e’; // e
print “\n”;
print $b[‘c’] ?: ‘e’; // Notice: Undefined index: c
print “\n”; >

More Details

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade