Back to Course |
PHP for Laravel Developers

IF-Else: Ternary and Null Safe Operators

When building applications, performing comparisons is very common. Recent PHP versions improved the good old "if-else" with a few shorter syntax options.


Ternary Operator: "? ... :"

The ternary operator is used to shorten the if/else.

Instead of writing this:

if (request()->has('customer_id')) {
return request()->get('customer_id');
} else {
return null;
}

You can write this:

request()->has('customer_id') ? request()->get('customer_id') : null

This ternary operator can be shortened using the "Elvis" "?:" operator.

request()->get('customer_id') ?: null

In this case, the returned value will be from the request or null.


Null coalescing: "??"

The null coalescing operator has been available since PHP 7.0. This operator is beneficial for arrays and assigning defaults when a variable is not set.

$username = $user->username ?? 'Anonymous';

In this example, if the username isn't set, the $username will be set to Anonymous.

Also, the null coalesce can be chained. Then, the first set will be returned.

Example from a Laravel Excel package:

src/Concerns/Exportable.php:

$headers = $headers ?? $this->headers ?? [];
$fileName = $fileName ?? $this->fileName ?? null;
$writerType = $writerType ?? $this->writerType ?? null;

In short, null coalescing is shorter than doing isset() in a ternary operator.

$result = $var ?? 'default';
// is a shorthand for
$result = isset($var) ? $var : 'default';

Null coalescing assignment: "??="

In PHP 7.4, a new operator ??= was added. It assigns value to a variable if it is null. Otherwise, it does nothing.

$username ??= 'Anonymous';

If the $username variable wasn't set anywhere else in your code only then it will be set to Anonymous.


Null Safe operator

PHP 8 introduced a new syntax called the null safe operator, which provides an optional chaining feature.

Instead of writing this:

$order = Order::latest()->first();
$invoiceNumber = null;
 
if ($order != null) {
if ($order->invoice != null) {
$invoiceNumber = $order->invoice->number;
}
}

Since PHP 8, you can write this:

$order = Order::latest()->first();
$invoiceNumber = $order?->invoice?->number;

The null safe operator and null coalescing operator are very similar. The null coalescing operator is useful when assigning a default value instead of a null.

$invoiceNumber = $order->invoice->number ?? 'Invoice number not set';

The null safe operator and the null coalescing operator can be used together.

$invoiceNumber = $order?->invoice->number ?? 'Order not found';

If an order is null, the default value set by the null coalescing operator will be assigned to a $invoiceNumber variable.

The null safe operator is only for reading data. You cannot assign values.

$order?->invoice?->number = 'ABC123';