Ternary, null coalescing and nullsafe

Three short forms of PHP replace a small branch with an expression: the ternary, the null coalescing operator and the nullsafe operator. Each one has a place where it reads better than if, and a size beyond which it does not.

The ternary operator

The ternary operator picks one of two values in a single expression: condition ? value_if_true : value_if_false. It shines for tiny choices such as labels, defaults, and plural forms.

<?php $age = 20; $label = $age >= 18 ? "adult" : "minor"; echo $label, PHP_EOL;

php ternary.php

adult

More examples live on the ternary operator page. Reach for a plain if statement as soon as either branch needs more than one action.

Null coalescing ??

The ?? operator returns its left side unless that side is missing or null, with no notice raised. It is the short form of isset checks, and it chains: PHP takes the first defined, non-null value from left to right.

<?php $query = array(); $name = $query["name"] ?? "guest"; $prefs = array("theme" => "dark"); $defaultTheme = "blue"; $theme = $prefs["theme"] ?? $defaultTheme ?? "light"; echo $name, PHP_EOL; echo $theme, PHP_EOL;

php coalesce.php

guest
dark

The name is missing from the query, so the default answers; the theme is the first defined value of three, so the chain stops there. A value that exists is kept even when it would be false in a condition, and only null sends the chain on.

Nullsafe ?->

The nullsafe operator short-circuits a whole method and property chain to null as soon as one link is null. It replaces pyramids of manual checks before every call in the chain.

<?php $full = new stdClass(); $full->customer = new stdClass(); $full->customer->address = new stdClass(); $full->customer->address->city = "Kyiv"; $empty = new stdClass(); $empty->customer = null; echo $full->customer?->address?->city ?? "unknown", PHP_EOL; echo $empty->customer?->address?->city ?? "unknown", PHP_EOL;

php nullsafe.php

Kyiv
unknown

The second order has no customer, so the first ?-> gives null, the rest of the chain is skipped and the ?? of the last line prints the fallback.

Keep it readable

Ternaries nest badly: two levels already force the reader to simulate the parser. Flatten nested choices into if and elseif, or into a match expression, so each outcome sits on its own line.

<?php $isMember = false; $isStudent = true; $fee = $isMember ? 0 : ($isStudent ? 5 : 10); echo $fee, PHP_EOL;

php nested.php

5

The same logic reads better as branches:

<?php $isMember = false; $isStudent = true; if ($isMember) { $fee = 0; } elseif ($isStudent) { $fee = 5; } else { $fee = 10; } echo $fee, PHP_EOL;

php branches.php

5

Both programs print 5, and the branches say why. A nested ternary without parentheses is a fatal error since PHP 8, with the message Unparenthesized `a ? b : c ? d : e` is not supported, so the parentheses above are not optional style.

Exercises

  1. Change $age in ternary.php to 17 and run it. Which value does the label take?
  2. Add a third level to the fee choice as a match expression with four outcomes, and check that every branch gives its own number.
  3. Give the query in coalesce.php a "name" key with the value null. Which name does the program print, and why?
  4. Set $empty->customer in nullsafe.php to an object without an address, then run it. What does the page print now, and where does the chain stop?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the ternary operator condition ? a : b return?

    Answer

    a when the condition is true, b otherwise

    The part before the colon answers a true condition and the part after it answers a false one.

  2. When does ?? take its right side?

    Answer

    When the left side is missing or null

    The null coalescing operator tests for existence and null only, so false, 0 and "" stay as they are.

  3. What does the nullsafe operator ?-> do when the value before it is null?

    Answer

    It skips the rest of the chain and gives null

    The chain short-circuits at the first null, so no later call runs and the whole expression is null.

  4. Why should a ternary not be nested two levels deep?

    Answer

    The reader has to simulate the parser to see which branch belongs where

    A nested ternary hides its order of evaluation, while if/elseif or match shows one outcome per line; PHP 8 also rejects it without parentheses.

  5. What does this program print? <?php echo true ? "yes" : "no";

    Answer

    yes

    The condition is true, so the value before the colon is the one that prints.

  6. What does this program print? <?php echo 0 ? "yes" : "no";

    Answer

    no

    Zero is false in a condition, so the ternary chooses the value after the colon.

  7. What does this program print? <?php $name = null; echo $name ?? "guest";

    Answer

    guest

    The left side is null, so the coalescing operator takes the right side and prints guest.

  8. What does this program print? <?php $empty = ""; var_dump($empty ?? "guest");

    Answer

    string(0) ""

    An empty string is defined and not null, so ?? keeps it and var_dump shows the empty string.

  9. What does this program print? <?php $a = array("x" => null); echo $a["x"] ?? "default";

    Answer

    default

    The key exists but its value is null, and ?? treats null exactly like a missing key.

  10. What does this program print? <?php $order = null; echo $order?->total ?? "no order";

    Answer

    no order

    The nullsafe operator gives null instead of an error, and then ?? prints the fallback text.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev