Simplifying if-else in PHP with Ternary and Null Safe Operators

Enamul Haque
4 min readApr 11, 2024

Recently, I gone through some articles, blogs and of course real life use to refactor existing PHP code. When refactoring them, I found some beautiful, simple yet effective use of PHP’s ternary and null safe operators. In our code we write a bunch of if-else obviously. By using the below concepts I believe we can reduce the number of lines as well as increase readability of our code a lot. Let’s start exploring.

Ternary Operator: “? … :”

The ternary operator ? : is a condensed form of the if-else statement in PHP, allowing you to execute different expressions based on a condition in a single line. It is used to shorten the if/else.

Instead of writing the below code:

$age = 20;
if($age > 18){
$status = 'adult';
}
else {
$status = 'minor';
}

You can simply write this:

$age = 20;
$status = ($age > 18) ? 'adult' : 'minor';

The “Elvis” operator ?:

in PHP is a shorthand for the ternary operator where the middle part (the expression to return if the condition is true) is omitted. It’s useful when you want to return the value of the condition itself if it’s true, or some other value if the condition is false.

Suppose you have a variable $age and you want to assign it to $validAge if $age is truthy (i.e., not null, 0, empty string, etc.), or assign a default value (in this case 18) if it’s not.

$age = 20; 
$validAge = $age ?: 18; // If $age is truthy, $validAge becomes $age's value, otherwise 18.

The null coalescing operator ?? in PHP is used to return the first operand if it exists and is not null; otherwise, it returns the second operand. This operator is particularly useful for providing default values for variables that might be null or undefined.

Let’s say you have an optional form field $age, and you want to ensure there’s always a value for $validatedAge.

$validatedAge = $age ?? 18;

null coalescing can assist you to skip use of isset() in code. the above code is a shorthand of -

$validatedAge = isset($age ) ? $age : 18;

The null coalescing assignment operator ??= in PHP is used to assign a value to a variable only if that variable is currently null or not set. This operator helps in setting default values for variables without overwriting existing non-null values.

$age ??=18;

In this example, if $age is null or not set before this line is executed, it will be assigned 18. If $age already has a non-null value, that value will remain as is. This operator is particularly useful for initializing variables with default values while preserving any existing non-null values.

The Null Safe operator ?-> in PHP is utilized for accessing properties or methods of an object that might be null without causing a runtime error. If the left-hand side of the operator is null, the entire expression short-circuits and evaluates to null without triggering an error for trying to access a property or method of a non-object. This operator is particularly useful in scenarios where you have a chain of object properties or method calls, and any part of the chain might be null.

Suppose you have an object $user that may have a profile property, which in turn may have a getAge() method. You want to get the age of the user, but there’s a possibility that either $user or $user->profile could be null.

Without the Null Safe operator, you’d have to explicitly check if $user and $user->profile are not null:

if ($user !== null && $user->profile !== null) {
$age = $user->profile->getAge();
} else {
$age = null;
}

With the Null Safe operator, you can simplify this to:

$age = $user?->profile?->getAge();

In this line, if $user or $user->profile is null, $age is immediately set to null without attempting to call getAge(). If $user and $user->profile are both not null, getAge() is called as expected.

This operator streamlines code that deals with nested properties or methods where a null value at any level should gracefully lead to a null result.

A short recap and helpful to keep note that, the null coalescing operator is useful when assigning a default value instead of a null.

$validatedAge = $age ?? 18;

On the other other hand, The null safe operator is only for reading data. You cannot assign values.

$age = $user?->profile?->getAge();

That’s it. happy coding!!!

--

--

Enamul Haque

Software Professional, Learner, Passionate to learn new things related to Software Engineering,