Home » PHP Tutorial » PHP Null Coalescing Operator

PHP Null Coalescing Operator

Summary : in this tutorial, you’ll learn about the PHP Null coalescing operator to assign a value to a variable if the variable doesn’t exist or null.

Introduction to the PHP null coalescing operator

When working with forms , you often need to check if a variable exists in the $_GET or $_POST by using the ternary operator in conjunction with the isset() construct. For example:

This example assigns the $_POST['name'] to the $name variable if $_POST['name'] exists and not null. Otherwise, it assigns the '' to the $name variable.

To make it more convenient, PHP 7.0 added support for a null coalescing operator that is syntactic sugar of a ternary operator and isset() :

In this example, the ?? is the null coalescing operator. It accepts two operands. If the first operand is null or doesn’t exist, the null coalescing operator returns the second operand. Otherwise, it returns the first one.

In the above example, if the variable name doesn’t exist in the $_POST array or it is null, the ?? operator will assign the string 'John' to the $name variable. See the following example:

As you can see clearly from the output, the ?? operator is like a gate that doesn’t allow null to pass through.

Stacking the PHP Null coalescing operators

PHP allows you to stack the null coalescing operators. For example:

In this example, since the $fullname , $first , and $last doesn’t exist, the $name will take the 'John' value.

PHP null coalescing assignment operator

The following example uses the null coalesing operator to assign the 0 to $counter if it is null or doesn’t exist:

The above statement repeats the variable $counter twice. To make it more concise, PHP 7.4 introduced the null coalescing assignment operator ( ??= ):

In this example, the ??= is the null coalescing assignment operator. It assigns the right operand to the left if the left operand is null. Otherwise, the coalescing assignment operator will do nothing.

It’s equivalent to the following:

In practice, you’ll use the null coalescing assignment operator to assign a default value to a variable if it is null.

  • The null coalescing operator ( ?? ) is a syntactic sugar of the ternary operator and isset() .
  • The null coalescing assignment operator assigns the right operand to the left one if the left operand is null.

Null Coalescing Operator in PHP: Embracing Graceful Defaults

Introduction.

The null coalescing operator introduced in PHP 7 provides a clean and succinct way to use a default value when a variable is null.

Getting Started with ‘??’

In PHP, the null coalescing operator (??) is a syntactic sugar construct that simplifies the task of checking for the existence and value of a variable. Prior to its introduction in PHP 7, developers would often utilize the isset() function combined with a ternary conditional to achieve a similar result. Let’s see this with a basic code example:

With the null coalescing operator, this simplifies to:

This approach immediately streamlines the code, making it more readable and easier to maintain.

Advancing with Null Coalescing

The operator is not only limited to simple variable checks but can be used with multiple operands, evaluating from left to right until it finds a non-null value. Let’s dive deeper with an advanced example:

This progresses through the $_GET, $_SESSION arrays, and ends with a literal if all else fails.

It also works seamlessly with functions and method calls. For instance:

In this scenario, if getUserFromDatabase($id) returns null, ‘fallback’ will be used.

Working with Complex Structures

The null coalescing operator is versatile, and can be directly applied to multi-dimensional arrays and even JSON objects. Consider the following example:

Let’s take it a step further with objects:

This code elegantly attempts to retrieve a profile picture, defaulting if nothing is returned.

Combining with Other PHP 7 Features

PHP 7 introduces other syntactic improvements such as the spaceship operator (<=>) for comparisons. Combine these with the null coalescing operator for powerful expressions. For example:

Real-World Scenarios

In real-world applications, embracing the null coalescing operator means focusing on the business logic rather than boilerplate checks. It particularly shines in scenarios involving configuration, forms, APIs, and conditional displays. The operator often becomes indispensable in modern PHP development workflows.

For instance, when processing API input:

Or, setting up a GUI with language fallbacks:

Good Practices and Pitfalls

While highly practical, there are scenarios where the null coalescing operator isn’t suitable. It should not replace proper validation and sanitization of user data, nor should it be overused in complex conditions where clearer logic may be needed for maintenance purposes. As with any tool in programming, using it judiciously is key.

Performance Implications

Performance-wise, the null coalescing operator is a favorable choice. Typically, it’s faster than combining isset() with a ternary operator due to reduced opcode generation. Let’s validate with a timed test:

You’re likely to notice slight but consistent speed advantages using the null coalescing operator.

The null coalescing operator in PHP streamlines default value assignment and contributes to cleaner code. As PHP continues to evolve, adopting such features not only leverages language efficiency but also enhances developer expressiveness and intent. In essence, the ?? operator fine-tunes the syntax dance that we perform every day as PHP developers.

Next Article: Why should you use PHP for web development?

Previous Article: Using 'never' return type in PHP (PHP 8.1+)

Series: Basic PHP Tutorials

Related Articles

  • Using cursor-based pagination in Laravel + Eloquent
  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)

Search tutorials, examples, and resources

  • PHP programming
  • Symfony & Doctrine
  • Laravel & Eloquent
  • Tailwind CSS
  • Sequelize.js
  • Mongoose.js
  • Web Development

What Is the Null Coalescing Assignment Operator in PHP?

  • Daniyal Hamid
  • 29 Nov, 2021

Starting with PHP 7.4+, you can use the null coalescing assignment operator ( ??= ). It is a shorthand to assign a value to a variable if it hasn't been set already. Consider the following examples, which are all equivalent:

The null coalescing assignment operator only assigns the value if $x is null or not set. For example:

This post was published 29 Nov, 2021 by Daniyal Hamid . Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post .

The PHP null coalescing operator (??) explained

by Nathan Sebhastian

Posted on Jul 11, 2022

Reading time: 2 minutes

null coalescing operator assignment php

The PHP null coalescing operator (also known as the double question mark ?? operator) is a new feature introduced in PHP 7.

The operator has two operands as follows:

The operator returns the first operand when the value is not null. Otherwise, it returns the second operand.

The operator allows you to set an if condition as shown below:

If the $_GET['user'] value is null in the example above, then assign the value nathan into the $user variable.

The null coalescing operator allows you to shorten a null check syntax that you need to do with the isset() function.

Before null coalescing operator, you may check for a null value using the ternary operator in conjunction with the isset() function like this:

When the user value is “unset” or null , assign nathan as the value of $user variable. Otherwise, it will assign $_POST['user'] as its value.

Stacking the null coalescing operands in PHP

The null coalescing operator allows you to stack as many operands as you need.

The operator will go from left to right looking for a non-null value:

When the value of $username is null or not set, PHP will look for the value of $first_name .

When $first_name is null or not set, PHP will look for the value of $last_name variable.

When $last_name variable is also null or not set, PHP will assign nathan as the value of $user variable.

Null coalescing assignment operator in PHP

The null coalescing operator can also be used to check a variable if it’s null.

You can then assign a value to the variable itself like this:

The syntax above means that PHP will check for the value of $user .

When $user is null or not set, then the value nathan will be assigned to it.

The code above is equivalent to the following isset() check:

And that’s how you assign a variable value using the null coalescing operator.

The PHP null coalescing operator is a new syntax introduced in PHP 7.

The operator returns the first operand if it exists and not null . Otherwise, it returns the second operand.

It’s a nice syntactic sugar that allows you to shorten the code for checking variable values using the isset() function.

Now you’ve learned how the null coalescing operator works in PHP. Nice work!

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.

Learn more about this website

Connect with me on Twitter

Or LinkedIn

Type the keyword below and hit enter

Click to see all tutorials tagged with:

PHP 7.4: Null Coalescing Assignment

With PHP 7.4 upcoming, it’s time to start exploring some of the new features that will be arriving alongside it. Here we cover the enhancements around the null coalescing operator , namely the introduction of the null coalescing assignment operator. (Sometimes referred to as the “null coalesce equal operator”)

In PHP 7 this was originally released, allowing a developer to simplify an isset() check combined with a ternary operator. For example, before PHP 7, we might have this code:

When PHP 7 was released, we got the ability to instead write this as:

Now, however, when PHP 7.4 gets released, this can be simplified even further into:

One case where this doesn’t work is if you’re looking to assign a value to a different variable, so you’d be unable to use this new option. As such, while this is welcomed there might be a few limited use cases.

So for example, this code from before PHP 7 could only be optimised once using the null coalescing operator, and not the assignment operator:

01 Jan 2020

  • development

IMAGES

  1. [Solved] Null coalescing operator (??) in PHP

    null coalescing operator assignment php

  2. Null coalescing assignment operator in PHP

    null coalescing operator assignment php

  3. PHP Null Coalescing Operators: Do You Use Them?

    null coalescing operator assignment php

  4. PHP : What is null coalescing assignment ??= operator in PHP 7.4

    null coalescing operator assignment php

  5. The PHP null coalescing operator (??) explained

    null coalescing operator assignment php

  6. Simplify Your Code with the PHP Null Coalescing Operator

    null coalescing operator assignment php

VIDEO

  1. Null coalescing operator in PHP

  2. The PHP Null Coalescing Operator: Make Your isset Usage More Concise and Easier to Read

  3. What is PHP Null Coalescing Operator

  4. PHP 7

  5. Learn PHP Operators

  6. PHP Null Coalescing Operators: Do You Use Them?

COMMENTS

  1. PHP Null Coalescing Operator

    In this tutorial, you'll learn about the PHP Null coalescing operator to assign a value to a variable if the variable doesn't exist or null.

  2. PHP: Assignment

    Assignment Operators. ¶. The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of …

  3. Null Coalescing Operator in PHP: Embracing Graceful Defaults

    The null coalescing operator in PHP streamlines default value assignment and contributes to cleaner code. As PHP continues to evolve, adopting such features not only …

  4. What Is the Null Coalescing Assignment Operator in PHP?

    Starting with PHP 7.4+, you can use the null coalescing assignment operator (??=). It is a shorthand to assign a value to a variable if it hasn't been set already. Consider the …

  5. The PHP null coalescing operator (??) explained

    The PHP null coalescing operator is a new syntax introduced in PHP 7. The operator returns the first operand if it exists and not null. Otherwise, it returns the second operand.

  6. PHP 7.4 : Null Coalescing Assignment Operator

    In PHP 7.4, we can use Null Coalescing Assignment Operator (??=) to do the same: <?php $student_name = null; $student_name ??= 'Default Name'; var_dump($student_name); Above, …

  7. PHP 7.4: Null Coalescing Assignment

    With PHP 7.4 upcoming, it’s time to start exploring some of the new features that will be arriving alongside it. Here we cover the enhancements around the null coalescing …