Ternary and Ternary Coalescing Operator in PHP

Published On27 May 2020

PHP supports various forms of ternary and coalescing operators. This is a quick post to catch-up to all ternary and coalescing operators supports in PHP.

1. Ternary Operator: cond ? expr1 : expr2

Ternary operator is a short form for an if/else block that executes exactly one expression each.

if ($marks >= 50) {
    $rank = 'pass';
}
else {
    $rank = 'fail';
}

The if/else block above is quite verbose and consumes more space for a simple expression. With the ternary operator, you can optimize this:

- if ($marks >= 50) {
-   $rank = 'pass';
- }
- else {
-   $rank = 'fail';
- }
+ $rank = $marks >= 50 ? 'pass' : 'fail';

Its syntax is follows:

result = condition ? expression-if-true : expression-if-false

PHP will execute condition condition, and if it evaluates to "true-ish" value (same semantics as an if() condition), value from expression-if-true is used. If condition evaluates to false, value from expression-if-false will be used.

An ideal use case of Ternary operator would be assignments that can have two values.

From PHP 8.0+, you can also throw an exception from a Ternary operator.

2. Shorthand Ternary Operator: cond ?: else-expr

Certain Ternary operator expressions can be simplified further. Consider the following Ternary expression:

$user = load_user() ? load_user() : false;

If the conditional expression is the same as the true-expression, it is possible to reduce this further:

- $user = load_user() ? load_user() : false;
+ $user = load_user() ?: false;

If load_user() function returns a false-ish value, $user will be assigned false. Otherwise, the return value of load_user() will be assigned.

Its syntax is:

result = cond ?: expression-if-false

The cond condition will be evaluated as if it's in an if() block, and the return value will be assigned to result if it is a truthy value. If it's a false-ish value (such as 0, "0", false, null, [], etc), the expression-if-false expression will be evaluated, and its return value will be assigned to result.

3. Null Coalescing Operator

Null Coalescing Operator provides a shorthand for isset() calls. It is often used to reduce excessive isset() calls. Null Coalescing operator calls isset() on the conditional expression, and the value will be returned.

- $result = isset($_GET['value']) ? $_GET['value'] : 'foo';
+ $result = $_GET['value'] ?? 'foo';

If $_GET['value'] is set (which behaves exactly the way isset() does), $_GET['value'] value will be assigned to $result. If it is not set, or null, foo will be assigned to $result.

result = variable ?? expression

PHP calls isset(variable), and variable will be assigned to result if variable is set. If it is not set, expression will be evaluated, and its value will be assigned to result.

4. Null Coalescing Assignment operator

Null Coalescing operator can be be further reduced in PHP 7.4, with Null Coalescing Assignment operator .

- $value = $value ?? 'foo';
+ $value ??= 'foo';

A word of caution

Be mindful when you chain ternary/coalescing operators. It is now required to use braces to make the intent clear if you absolutely have to use ternary/coalescing operators.

Null Coalescing Assignment operator is relatively new in PHP (added in PHP 7.4), so you code might not work in older PHP versions if you decide to use that operator.

These operators are syntax sugar only, and do not provide any meaningful performance difference compared to good ol' if/else blocks. When the intent is not clear, it is recommended to go with if/else blocks although they make the code slightly verbose

Recent Articles on PHP.Watch

All ArticlesFeed 
How to fix `mysql_native_password` not loaded errors on MySQL 8.4

How to fix mysql_native_password not loaded errors on MySQL 8.4

How to fix the SQLSTATE[HY000] [1524] Plugin 'mysql_native_password' is not loaded errors caused in MySQL 8.4 no longer enabling the mysql_native_password plugin by default.
How to fix PHP Curl HTTPS Certificate Authority issues on Windows

How to fix PHP Curl HTTPS Certificate Authority issues on Windows

On Windows, HTTPS requests made with the Curl extension can fail because Curl has no root certificate list to validate the server certificates. This article discusses the secure and effective solutions, and highlights bad advice that can leave PHP applications insecure.
AEGIS Encryption with PHP Sodium Extension

AEGIS Encryption with PHP Sodium Extension

The Sodium extension in PHP 8.4 now supports AEGIS-128L and AEGIS256 Authenticated Encryption ciphers. They are significantly faster than AES-GCM and CHACHA20-POLY1305. This article benchmarks them and explains how to securely encrypt and decrypt data using AEGIS-128L and AEGIS256 on PHP.
Subscribe to PHP.Watch newsletter for monthly updates

You will receive an email on last Wednesday of every month and on major PHP releases with new articles related to PHP, upcoming changes, new features and what's changing in the language. No marketing emails, no selling of your contacts, no click-tracking, and one-click instant unsubscribe from any email you receive.

Support PHP.Watch — If you find the articles, version information, Codex, and other PHP.Watch contributions useful, consider supporting through GitHub Sponsors. Your sponsorship helps dedicate more time to creating valuable content and improving the PHP community. Together, we can keep the momentum going — thank you for your support!

Thanks to the highest tier sponsor: @TomasVotruba for your generous support to keep PHP.Watch moving 💜