PHP
ProgrammingTips & Tricks

What is PHP null coalescing operator (??)

Introduction

In the world of web development, PHP remains a popular choice for building dynamic and interactive websites. To streamline coding and enhance the readability of PHP scripts, developers often rely on various operators. One such operator that has gained prominence in recent years is the PHP Null Coalescing Operator, denoted by ??. In this article, we will delve into the details of this operator, its purpose, and how it simplifies conditional assignments in PHP.

What is PHP null coalescing operator?

In this article, we will talk about PHP null coalescing operator. If you use PHP, you will find out that there’s actually different ways to do coding. It provides different functions or syntax but some works the same just different way to write it.

There’s a useful shorthand operator which is the “??” (or null coalescing) operator. It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

In short, it’s actually just a isset() feature in a handy operator.

Understanding the Need

Before diving into the Null Coalescing Operator, it’s essential to grasp the problem it aims to solve. PHP often encounters situations where variables may be undefined or contain null values. Handling such cases with traditional conditional checks can be cumbersome and lead to verbose code. For instance, consider the following code snippet:

if(isset($name)){
   $username = $name;
} else {
   $username = "Guest";
}

While this code adequately assigns a default value “Guest” to $username if $name is not set, it is not the most elegant or efficient solution. This is where the Null Coalescing Operator comes into play.

The PHP Null Coalescing Operator (??)

Introduced in PHP 7, the Null Coalescing Operator, ??, simplifies the process of assigning default values to variables that may be null or undefined. Its syntax is concise and easy to understand. Here’s how it works:

$username = $name ?? "Guest";

In this single line of code, we achieve the same result as the earlier example. If $name is set and not null, $username will be assigned the value of $name. However, if $name is either null or undefined, $username will be assigned the default value “Guest.”

This operator effectively condenses the conditional check and assignment into a single line, making code more readable and reducing redundancy.

Using Multiple Coalescing Operators

The Null Coalescing Operator can also be chained to handle multiple variables and default values. This enables developers to create complex conditional assignments in a clear and concise manner. Here’s an example:

$firstName = $first ?? $user['first'] ?? "Guest";

In this example, the code first checks if $first is defined and not null. If it is, $firstName is assigned the value of $first. If not, it checks if $user['first'] is defined and not null, and assigns that value to $firstName. If both variables are null or undefined, $firstName defaults to “Guest.”

More Examples

These 2 lines below returns the same results. The first one is just using the normal isset() operator and the second one is using the shorthand operator.

$foo = isset($bar) ? $bar : 'not exists';
$foo = $bar ?? 'not exists';

If we echo $foo, it will return the value “not exists”.

In particular, this operator does not emit a notice or warning if the left-hand side value does not exist, just like isset(). This is especially useful on array keys.

If we assign a value to $bar, it will then return the $bar value.

$bar = 'test';
$foo = $bar ?? 'not exists';
echo $foo; //returns test;

Also note that if we assign the boolean false value to $bar, it will returns an empty value. Because the $bar variable does exists and assigned with “false”.

Benefits of the PHP Null Coalescing Operator

  1. Conciseness: The Null Coalescing Operator reduces the need for lengthy and repetitive conditional checks, resulting in cleaner and more readable code.
  2. Efficiency: It can enhance code execution by eliminating unnecessary evaluations of conditional expressions.
  3. Reduced Errors: With fewer lines of code, there is a reduced chance of introducing logical errors or overlooking edge cases.
  4. Simplicity: Developers can quickly understand and work with code that uses the Null Coalescing Operator, which can lead to faster development and easier maintenance.

Conclusion

The PHP Null Coalescing Operator, denoted by ??, is a valuable addition to the language that simplifies conditional assignments, particularly when dealing with null or undefined variables.

Its concise syntax and ability to handle multiple variables and default values make it a powerful tool for web developers, enhancing code readability and efficiency.

As PHP continues to evolve, understanding and leveraging operators like the Null Coalescing Operator is crucial for writing clean and maintainable code in the ever-changing landscape of web development.

Source : https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

Check out https://www.kintechie.com/php-errors-deprecation-notice/ for another PHP tip!