Home ยป PHP Null Coalescing Operator Tutorial with Examples

PHP Null Coalescing Operator Tutorial with Examples

The null coalescing operator (??) was introduced in PHP 7. It is used to simplify common coding patterns where you want to check if a variable or expression is set and not null.

The null coalescing operator allows you to return a default value when a variable is not set or is null, making your code cleaner and easier to read.

Syntax:

$result = $a ?? $b;

If $a is set and not null, $a is returned.
If $a is not set or is null, $b is returned.

This is particularly useful when working with arrays, forms, or optional parameters where a default value might be required.

1. Basic Usage of the Null Coalescing Operator

The null coalescing operator checks if the left-hand value is set and not null. If the left-hand value is set, it returns that value; otherwise, it returns the right-hand value.

Example:

<?php
// Example 1: Variable is set and not null
$var1 = "Hello, World!";
$result = $var1 ?? "Default Value";
echo $result; // Outputs: Hello, World!

// Example 2: Variable is null
$var2 = null;
$result = $var2 ?? "Default Value";
echo $result; // Outputs: Default Value

// Example 3: Variable is not set
$result = $var3 ?? "Default Value";
echo $result; // Outputs: Default Value (since $var3 is not defined)
?>

In this Example:

$var1 is set and not null, so it is returned.
$var2 is null, so the default value “Default Value” is returned.
$var3 is not defined, so the default value is returned.

2. Using the Null Coalescing Operator with Arrays

The null coalescing operator is particularly useful when working with arrays, such as when retrieving values from a form or an associative array, where a key might not exist.

Example (Accessing Array Values):

<?php
$user = [
    'name' => 'John',
    'email' => 'john@example.com'
];

// Access existing key
$name = $user['name'] ?? 'Guest';
echo $name; // Outputs: John

// Access non-existing key (returns default value)
$age = $user['age'] ?? 'Not specified';
echo $age; // Outputs: Not specified
?>

Here, the name key exists, so “John” is returned.
The age key does not exist, so the default value “Not specified” is returned.

3. Chaining the Null Coalescing Operator

You can chain multiple null coalescing operations together. The first non-null value encountered will be returned.

Example:

<?php
$var1 = null;
$var2 = null;
$var3 = "Value from var3";

$result = $var1 ?? $var2 ?? $var3 ?? "Default Value";
echo $result; // Outputs: Value from var3
?>

In this Example:

$var1 and $var2 are null, so the operator moves to $var3.
Since $var3 is set and not null, its value is returned (“Value from var3”).
The “Default Value” is ignored because $var3 is valid.

4. Null Coalescing Operator vs Ternary Operator

The null coalescing operator (??) is similar to the ternary operator (?:), but the main difference is that the ternary operator checks whether a condition is true or false, while the null coalescing operator checks if a value is set and not null.

Ternary Operator

Example:

<?php
$var = null;
$result = isset($var) ? $var : "Default Value";
echo $result; // Outputs: Default Value
?>

Null Coalescing Operator

Example:

<?php
$var = null;
$result = $var ?? "Default Value";
echo $result; // Outputs: Default Value
?>

The null coalescing operator (??) is more concise and does not require isset(). It directly checks if a variable is set and not null, which simplifies the code.

5. Form Handling with the Null Coalescing Operator

The null coalescing operator is extremely useful when dealing with form submissions, as it provides a quick way to check whether form fields have been submitted or not.

Example (Handling Form Input):

<?php
// Simulating a form submission (in a real-world scenario, this would come from $_POST or $_GET)
$_POST = [
    'username' => 'john_doe'
];

// Check if the form field is set, and provide a default value if not
$username = $_POST['username'] ?? 'Anonymous';
$age = $_POST['age'] ?? 'Not provided';

echo "Username: $username<br>"; // Outputs: Username: john_doe
echo "Age: $age<br>"; // Outputs: Age: Not provided
?>

In this example, the username field is submitted, so its value (“john_doe”) is returned.
The age field is not submitted, so the default value (“Not provided”) is returned.

6. Null Coalescing Assignment Operator (??=)

As of PHP 7.4, a shorthand for assigning a default value to a variable if it’s not set or null was introduced. This is known as the null coalescing assignment operator (??=).

Syntax:

$var ??= 'Default Value';

If $var is not set or is null, it will be assigned the value ‘Default Value’.

Example:

<?php
$var = null;

// Assign a value if $var is null or not set
$var ??= 'Default Value';
echo $var; // Outputs: Default Value

// If $var already has a value, it won't be reassigned
$var ??= 'Another Value';
echo $var; // Outputs: Default Value (remains unchanged)
?>

In this example, $var is assigned the default value (“Default Value”) because it is initially null.
When the null coalescing assignment operator is used again, it doesn’t change the value of $var because it already has a valid value.

7. Using the Null Coalescing Operator with Functions

You can also use the null coalescing operator when working with function return values.

Example:

<?php
// A function that might return null
function getUserName() {
    return null; // Simulating no user found
}

$username = getUserName() ?? 'Guest';
echo $username; // Outputs: Guest
?>

In this example, if the getUserName() function returns null, the null coalescing operator ensures that the default value “Guest” is used.

Key Points:

  • Check if a value is set and not null:
    • The null coalescing operator returns the left-hand value if it exists and is not null; otherwise, it returns the right-hand value.
  • Chaining is allowed:
    • You can chain multiple null coalescing operators to check several variables in sequence.
  • Null Coalescing Assignment Operator:
    • The null coalescing assignment operator (??=) provides a shorthand for assigning a default value to a variable if it’s null.
  • Works well with arrays:
    • It’s commonly used when accessing array values, especially in form data ($_POST or $_GET).

Conclusion

The null coalescing operator (??) is a powerful tool in PHP that simplifies the process of checking whether a value is set or null.

It helps reduce the verbosity of code that requires multiple checks, particularly when working with arrays, forms, or optional parameters.

Its shorthand version, the null coalescing assignment operator (??=), introduced in PHP 7.4, further improves code readability by making assignments cleaner and more concise.

You may also like