Three cats as illustrations ponder over Ternary Operaror vs Null Coalescing Operator

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

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.

See also

More techdoks and snippets

Shortcode E-Mail Obfuscator

The following shortcode snippet is useful for disguising emails to protect them from SPAM. Please note that this method only works if Javascript is activated. In addition, there is no 100%igen protection against bots,...

Elementor popup / flyout menu no longer closes for mobile view

Elementor: Version 3.72 Behaviour: An Elementor popup opens, but no longer closes (when clicking on icon or Esc or other triggers). If you look in the source code, you will find the Javascript error message: "Elementor t.entrance_animation_duration is undefined" Cause:...

PHPStorm: Local Changelist in Git Tool disappeared

Problem: Local Change List under PHPStorm is missing in the Git Tool Solution: From time to time I had the phenomenon that the Local Changelist (the files in my version control) were not visible as tabs in the Git tool....

Variable not available in blade component

Problem: The parameter transfer of a blade attribute does not work, the variable in the component is empty. There is no error message, but the variable does not appear to have been passed. Solution: The error may lie in the usage...

WP CLI Error: Error establishing a database connection.

Appearance: Submitting commands via WP CLI, but WordPress in the browser works. This error often occurs when the WP CL interpreter cannot correctly interpret the database connection in wp-config.php. Solution: In 99% of all cases the...

Convert Px to SEM / EM very quickly with Alfred

There is a wonderful Alfred workflow on the Mac that converts Px to Rem: Download direct link: https://raw.githubusercontent.com/vitorgalvao/requested-alfred-workflows/master/Workflows/PxRemEm.alfredworkflow Simply install, then type CMD-Space: Alfred Bar "pxrem" and enter the number in pixels. The conversion to REM will...

Setting up XDebug with PHPStorm and Valet Development Environment

Preparation: Homebrew should be installed Valet should be installed and running: https://laravel.com/docs/7.x/valet Browser extension for PHPSTORM should be installed: https://www.jetbrains.com/help/phpstorm/browser-debugging-extensions.html gerry@webgarten ~ % brew install pecl gerry@webgarten ~ % pecl install xdebug In case of error message: Warning:...