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 prefers $ food preference.";
Code language: PHP (php)
Zero 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' => ['favorite toy' => 'Laser pointer'],
'Fur ball' => ['favorite toy' => zero],
'Brett Pit' => [],
'Nuclear danger' => ['favorite toy' => 'Love'],
];
foreach ($catsData as $name => $data) {
1TP5Favorite toy = $data['favorite toy'] ?? 'Old plastic mouse';
// The same as Ternary:
// $favorite toy = isset($data['favoritetoy']) && $data['favoritetoy'] !== null ? $daten['lieblingsspielzeug'] : 'Old plastic mouse'
// With long variable names, you can clearly see the advantage of the ? operator.
echo "$name loves to play with toys $favorite toys.\n";
}
Code language: PHP (php)
Issue:
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 normalize 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.