PHP Tips: Using the Null Coalescing Operator for Cleaner Code

The null coalescing operator (??) is a syntactic sugar that checks if a variable is set and is not null. If the variable exists and is not null, its value is returned. Otherwise, a default value is returned. This operator is particularly useful when dealing with variables that might not be initialized or when fetching values from arrays (e.g., superglobals like $_GET, $_POST).

Why to use the Null Coalescing Operator?

Before the introduction, developers commonly used the ternary operator or the isset() function to achieve similar results. However, these methods were more verbose and less readable. This operator simplifies this process, reducing potential errors and making the code cleaner.

Traditional Approach with Ternary Operator

$variable = isset($value1) ? $value1 : $value2;

Approach with Null Coalescing Operator

$variable = $value1 ?? $value2;

Syntax

The syntax for the null coalescing operator is straightforward:

<?php

$variable = $value1 ?? $value2;?>

If $value1 is set and not null, $variable will be assigned its value. Otherwise, $variable will be assigned $value2.

Examples
Basic Usage
With Undefined Variable

Consider the following example:

<?php

$test = $_GET[‘hello’] ?? ‘default value’;
echo $test; // Outputs: ‘default value’ if ‘hello’ is not set
?>

In this case, if $_GET[‘hello’] is not set, ‘default value’ will be assigned to $test.

With Defined Variable

Now, let’s see an example with a defined variable:

<?php

$_GET[‘hello’] = ‘bar’;
$test = $_GET[‘hello’] ?? ‘default value’;
echo $test; // Outputs: ‘bar’

?>

Here, since $_GET[‘hello’] is set to ‘bar’, $test will be assigned the value ‘bar’.

Chaining Null Coalescing Operators

You can chain multiple null coalescing operators:

<?php

$test = $var1 ?? $var2 ?? ‘default value’;
?>

In this case, $test will be assigned the first non-null value among $var1 and $var2. If both are null, ‘default value’ will be assigned to $test.

Combining with Ternary Operator

The null coalescing operator can also be combined with the ternary operator for more complex logic:

<?php

$test = $_GET[‘hello’] ?? ($_POST[‘hello’] ?? ‘default value’);
echo $test; // Outputs value from $_GET[‘hello’] or $_POST[‘hello’] or ‘default value’

?>

In this example, $test will be assigned the value from $_GET[‘hello’] if it is set and not null. If $_GET[‘hello’] is not set, it will check $_POST[‘hello’]. If neither is set, ‘default value’ will be assigned.

 

By:- Arshdeep Singh

 

Also Read :-

State Management in React Native with React Hooks and Context API

Accent-Color Property in CSS

Also Visit:-

https://inimisttech.com/

 

Leave a Reply