Ternary Operator ?: versus Null Coalescing Operator ?? versus Null Coalescing Assignment Operator ??= explained by cats

10.04.2024

Picture of a beautifully tidy garden

In short:

PHP offers two useful operators to simplify condition checks: the ternary operator (?:) and the Zero coalescing operator (??).

Both operators are used to Streamline code and improve readabilitybut they differ in their functionality and application.

The Ternary Operator is an abbreviation for:

if(human_is_asleep()) {
   be_as_loud_as_you_can();
} else {
   sleep();
}Code language: PHP (php)

The same with the ternary operator:

human_is_asleep() ? be_as_loud_as_you_can() : sleep();

Since ternary operators are mainly there to increase readability, nested ternary operators are not a good idea because they worsen readability:


$alter = 3; // Age of the cat in years
$weight = 6; // Weight of the cat in kilograms

// Determination of food preference with a nested ternary operator
$FoodPreference = $alter < 2 ? ($weight < 3 ? 'Young animal wet food (very expensive)' : 'Young animal dry food' :
                  ($weight < 4 ? 'Adult wet food' : 'Adult dry food');

echo "This cat favours $ food preference.";Code language: PHP (php)

Null coalescing operator (??)

The null coalescing operator ("coalescing" = "merging") checks for the presence of a value and is used with the syntax Expression1 ?? Expression2 used. If Printout1 exists and not zero is Printout1 is returned; otherwise Printout2 evaluated and returned. Particularly useful in the following example:

$catData = [
    Maunzi' => ['favourite toy' => 'Laser pointer'],
    'Fur ball' => ['favourite toy' => zero],
    Brett Pit' => [],
    'Nuclear danger' => ['favourite toy' => 'Love'],
];
foreach ($catsData as $name => $data) {
    1TP5Favourite toy = $data['favourite toy'] ?? 'Old plastic mouse';
    // The same as Ternary:
    // $favourite toy = isset($data['favourite toy']) && $data['favourite toy'] !== null ? $daten['favourite toy'] : 'Old plastic mouse' 
   // For long variable names, you can clearly see the advantage of the ? operator.
    echo "$name loves to play with toys $favourite toys.\n";
}Code language: PHP (php)

results in:

Maunzi loves to play with toy laser pointers.
Fellkugel loves to play with toy Olle Plastikmaus.
Brett Pit loves to play with toy Olle Plastikmaus.
Nuclear danger loves to play love with toys. 😸

In this case, the zero coalescing operator was used to undefined Inputs for cat toys a Assign default value.

With zero coalescing assignment, an assignment is performed immediately, it is an abbreviation in the abbreviation. It is particularly useful when you want to normalise nested indexed arrays, for example:


// $daten['katzen'][$i]['rasse'] ??= 'European Shorthair'; 
// is easier to read and maintain than the equivalent:
// $daten['katzen'][$i]['rasse'] = $daten['katzen'][$i]['rasse'] ?? 'European Shorthair';
Code language: JSON / JSON with Comments (json)

That was a short excursion into the world of Cats PHP operators. Have fun coding.