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

The PHP null coalescing operator (??) explained

by Nathan Sebhastian

Posted on Jul 11, 2022

Reading time: 2 minutes

php nullish assignment

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 nullish assignment

Buckle up, fellow PHP enthusiast! We're loading up the rocket fuel for your coding adventures...

  • Best Practices ,

php nullish assignment

PHP null coalescing operator

Hello everyone, I'm relatively new to PHP and I recently came across the term "null coalescing operator." I have heard people mention it, but I'm not entirely sure what it does and how it can be used in my code. To give you some context, I am working on a project where I need to handle situations where variables might be null. I've been using conditionals and ternary operators to check for null values, but I've heard that the null coalescing operator could simplify my code. So my question is, what exactly is the null coalescing operator in PHP? How does it work and what are some practical use cases for it? I would appreciate it if someone could explain it to me in a way that is beginner-friendly and provide some code examples to illustrate its usage. Thank you in advance for your help!

All Replies

kreiger.kieran

Hey there! I've been using the null coalescing operator in my PHP projects for a while now, and I must say, it's a fantastic addition to the language. As the name suggests, it helps in tackling situations where you need to handle null values. Here's how it works: the null coalescing operator (`??`) allows you to assign a default value to a variable if it is null. It's a concise way to check if a variable is null and provide an alternative value in a single expression. For example, let's say you have a variable `$name` that might be null. Instead of using an if statement or ternary operator, you can use the null coalescing operator like this: $defaultName = "Guest"; $fullName = $name ?? $defaultName; In this case, if `$name` is not null, the value of `$name` will be assigned to `$fullName`. However, if `$name` is null, `$defaultName` will be assigned to `$fullName`. It's a neat shortcut that keeps your code clean and concise. Another use case is when working with arrays. Suppose you have an associative array `$data` that may or may not have a key called `'email'`. To assign a default email if the `'email'` key is missing or null, you can use the null coalescing operator like this: $defaultEmail = "[email protected]"; $email = $data['email'] ?? $defaultEmail; If `$data['email']` exists and is not null, `$email` will be assigned its value. Otherwise, the default email address will be assigned. I've found the null coalescing operator to be handy in scenarios where you want to provide fallback values without writing lengthy if-else blocks or ternary statements. It definitely simplifies the code and makes it more readable. I hope this helps you understand and use the null coalescing operator effectively in your PHP projects. Feel free to ask if you have any more questions!

dwight42

Hey everyone, I just wanted to chime in and share my experience with the null coalescing operator in PHP. I've been using it extensively in my projects, and it has proven to be a real time-saver. One particular use case where the null coalescing operator shines is when dealing with form input data. Typically, you would handle form submissions by checking if each field has a value or is null before using it. With the null coalescing operator, you can simplify this process and handle default values elegantly. Let's say you have a form with various inputs, such as name, email, and phone number. To avoid errors when these fields are left blank, you can utilize the null coalescing operator to assign default values. php $name = $_POST['name'] ?? "Anonymous"; $email = $_POST['email'] ?? "[email protected]"; $phone = $_POST['phone'] ?? "N/A"; In this example, if the corresponding `$_POST` variable is not null, the value will be assigned to the respective variable. However, if the field is null (left blank in the form), the null coalescing operator will assign the provided default value instead. This approach saves you from writing verbose conditional statements to handle each form input individually. It condenses the code and makes it more readable. Not only does the null coalescing operator simplify handling null values, but it also allows for cleaner code in cases where API responses or database query results may contain null values. Instead of manually checking each value, you can leverage the operator and set appropriate defaults or fallback values as needed. Overall, the null coalescing operator in PHP is a powerful tool for gracefully handling null values and reducing code complexity. I highly recommend integrating it into your PHP projects for smoother data handling. If you have any questions or need further clarification, feel free to ask. Happy coding!

Related Topics

  • Best PHP Projects [with Sourcecode]
  • PHP vs Typescript
  • PHP vs MongoDB
  • PHP vs HTML
  • How to create API in PHP?
  • Is PHP an OOP language?
  • PHP vs Bootstrap
  • PHP vs Dotnet
  • What is the best way to Learn PHP?

pdenesik

Hello all, I couldn't resist joining the discussion on the null coalescing operator in PHP. As a seasoned PHP developer, I can't stress enough how much it has improved my code readability and reduced boilerplate code. One practical use case I'd like to share is dealing with database results. We often fetch data from a database and assign it to variables, but sometimes certain fields may be null. That's where the null coalescing operator comes in handy. Imagine a scenario where you're fetching user records and want to display their names. Some users may not have specified their first name, so the database field would be null. Instead of writing lengthy if-else statements, the null coalescing operator provides an elegant solution. php $firstName = $user['first_name'] ?? "Unknown"; $lastName = $user['last_name'] ?? "Unknown"; With just a single line for each variable, we're able to handle null values effortlessly. If `first_name` or `last_name` is null, the corresponding variable will be assigned the default value of "Unknown". This not only streamlines the code but also improves legibility. It becomes much easier to track the intention of assigning default values to variables without bloating the codebase. Additionally, the null coalescing operator is a blessing when working with APIs. Sometimes APIs may have optional fields that could be null if not provided. By employing the null coalescing operator, you can quickly set fallback values to ensure your code continues to function seamlessly. To sum it up, the null coalescing operator is an essential tool that simplifies handling null values in PHP. Whether it's handling user input, database records, or API responses, this operator proves to be an elegant and efficient solution. If you have any questions or need further insights, feel free to ask. Happy coding, everyone!

More Topics Related to PHP

  • What are the recommended PHP versions for different operating systems?
  • Can I install PHP without root/administrator access?
  • How can I verify the integrity of the PHP installation files?
  • Are there any specific considerations when installing PHP on a shared hosting environment?
  • Is it possible to install PHP alongside other programming languages like Python or Ruby?

More Topics Related to Code Examples

  • What is the syntax for defining constants in PHP?
  • How do I access elements of an array in PHP?
  • How do I declare a null variable in PHP?
  • What are resources used for in PHP?

More Topics Related to Variables

  • How do I declare a variable in PHP?
  • What is the difference between a constant and a variable in PHP?
  • How do I handle type casting in PHP?
  • Can a variable name start with a number in PHP?
  • Are variables case-sensitive in PHP?

Popular Tags

  • Best Practices
  • Web Development
  • Documentation
  • Implementation

php nullish assignment

New to LearnPHP.org Community?

John Morris

Ready to learn even more PHP ? Take my free Beginner’s Guide to PHP video series at https://johnmorrisonline.com/learnphp

Get this source code along with 1000s of other lines of code (including for a CMS, Social Network and more) as a supporting listener of the show at https://johnmorrisonline.com/patreon

P.S. If you liked the show, give it a like and share with the communities and people you think will benefit. And, you can always find all my tutorials, source code and exclusive courses on Patreon .

Join 7,700 Other Freelancers Who've Built Thriving Freelance Businesses

Over 7,700 other freelancers have started thriving freelance businesses using the information on this blog. Are you next? Subscribe below to get notified whenever a new article is posted and create your own success story:

You might also like

Complete HTML Tutorial for Beginners

Complete HTML Tutorial for Beginners

Description Are you interested in starting a career in web development? This beginner-friendly HTML tutorial is the perfect starting point for you. In this comprehensive

25 Upwork Proposal Mistakes

25 Common Upwork Proposal Mistakes to Avoid at All Costs

Your ability to write high-quality proposals will determine your success on Upwork. Period. It’s also no secret that creating a great proposal requires time, effort,

45 Upwork Proposal Techniques

45 Proven Techniques to (Drastically) Improve Your Upwork Proposal Writing Skills

As a platform connecting talented freelancers with clients from all around the globe, Upwork offers incredible opportunities to showcase your skills and secure rewarding projects.

32 Upwork Proposal Hacks

Cheat Codes: 32 Upwork Proposal Hacks You Need to Know

Crafting an effective Upwork proposal is a crucial skill for freelancers seeking success on the platform. Your proposal serves as your first impression and can

Frustrated Freelancer

Why Your Upwork Proposals Aren’t Getting Accepted (And How to Fix It)

As a freelancer on Upwork, you know that submitting a proposal is just the first step in the process of landing a job. But what

woman raising her hands up while sitting on floor with macbook pro on lap

How to Make Your Upwork Proposal Unforgettable: Top Tips for Leaving a Lasting Impression

Welcome to the wonderful world of Upwork proposals! If you’re looking to land that dream project, then you’ll need to learn how to make a

John Morris

JOHN MORRIS

I’m a 15-year veteran of freelance web development. I’ve worked with bestselling authors and average Joe’s next door. These days, I focus on helping other freelancers build their freelance business and their lifestyles.

Latest Shorts

Can I get a job just knowing HTML and CSS?

Is it still worth learning HTML and CSS in 2023?

How do I teach myself HTML?

Where do I write my HTML code?

What is the starting code for HTML?

Which software is best for HTML?

Latest Posts

Success stories, ready to add your name here.

Tim Covello

Tim Covello

75 SEO and website clients now. My income went from sub zero to over 6K just last month. Tracking 10K for next month. Seriously, you changed my life.

Michael Phoenix

Michael Phoenix

By the way, just hit 95K for the year. I can’t thank you enough for everything you’ve taught me. You’ve changed my life. Thank you!

Stephanie Korski

Stephanie Korski

I started this 3 days ago, following John’s suggestions, and I gained the Upwork Rising Talent badge in less than 2 days. I have a call with my first potential client tomorrow. Thanks, John!

Jithin Veedu

Jithin Veedu

John is the man! I followed his steps and I am flooded with interviews in a week. I got into two Talent clouds. The very next day, I got an invitation from the talent specialists from Upwork and a lot more. I wanna shout out, he is the best in this. Thanks John for helping me out!

Divyendra Singh Jadoun

Divyendra Singh Jadoun

After viewing John’s course, I made an Upwork account and it got approved the same day. Amazingly, I got my first job the very same day, I couldn’t believe it, I thought maybe I got it by coincidence. Anyways I completed the job and received my first earnings. Then, after two days, I got another job and within a week I got 3 jobs and completed them successfully. All the things he says seem to be minute but have a very great impact on your freelancing career.

Sarah Mui

I’ve been in an existential crisis for the last week about what the heck I’m doing as a business owner. Even though I’ve been a business for about a year, I’m constantly trying to think of how to prune and refine services. This was very personable and enjoyable to watch. Usually, business courses like this are dry and hard to get through…. repeating the same things over and over again. This was a breath of fresh air. THANK YOU.

Waqas Abdul Majeed

Waqas Abdul Majeed

I’ve definitely learnt so much in 2.5 hours than I’d learn watching different videos online on Youtube and reading tons of articles on the web. John has a natural way of teaching, where he is passionately diving in the topics and he makes it very easy to grasp — someone who wants you to really start running your business well by learning about the right tools and implement them in your online business. I will definitely share with many of the people I know who have been struggling for so long, I did find my answers and I’m sure will do too.

Scott Plude

Scott Plude

I have been following John Morris for several years now. His instruction ranges from beginner to advanced, to CEO-level guidance. I have referred friends and clients to John, and have encouraged my own daughter to pay attention to what he says. All of his teachings create wealth for me (and happiness for my clients!) I can’t speak highly enough about John, his name is well known in my home.

php nullish assignment

John is a fantastic and patient tutor, who is not just able to share knowledge and communicate it very effectively – but able to support one in applying it. However, I believe that John has a very rare ability to go further than just imparting knowledge and showing one how to apply it. He is able to innately provoke one’s curiosity when explaining and demonstrating concepts, to the extent that one can explore and unravel their own learning journey. Thanks very much John!

Mohamed Misrab

Misrab Mohamed

John has been the most important person in my freelance career ever since I started. Without him, I would have taken 10 or 20 years more to reach the position I am at now (Level 2 seller on Fiverr and Top Rated on Upwork).

© 2021 IDEA ENGINE LLC. All rights reserved

CodedTag

  • Null Coalescing Operator

The PHP null coalescing operator, denoted by ?? , is a convenient feature introduced in PHP 7 that simplifies the way developers handle the default values for variables that may be null.

It provides a concise and readable syntax for dealing with potentially null values without the need for verbose ternary expressions.

Let’s move into its syntax.

Null Coalescing Operator Syntax

The syntax of the PHP null coalescing operator ( ?? ) is quite straightforward. It is used to handle situations where a variable may be null or not set, providing a default value if the variable is null. The basic syntax is as follows:

  • $variable : The variable you want to check for null.
  • $value : The value to use if $variable is not null.
  • $default : The default value to use if $variable is null.

The following section provides an overview of how the null coalescing operator works. Let’s proceed.

How does the Null Coalescing Operator work?

This operation occurs in a single line, making the code more readable and concise compared to traditional conditional statements.

Here’s an example that shows you how it works:

The operator checks if the variable on the left side ( $variable in this case) is set and is not null. If it is set and not null, the expression evaluates to the value of $variable . If $variable is not set or is null, the expression evaluates to the value of $default .

This operator is especially useful when dealing with user input, configuration settings, or other scenarios where a variable might be null, and you want to provide a default value in case it is.

By moving into the section below, you will learn more about the null coalescing operator in PHP through examples.

Null Coalescing Operator Examples

Here is a basic example:

In this example, we are trying to retrieve the value of the username parameter from the $_GET array. If the username parameter exists and is not null, it will be assigned to the $username variable. However, if the username parameter is null or does not exist, the value ‘Guest’ will be assigned to $username . This is because of the null coalescing operator.

The null coalescing operator can also be chained together to provide default values for multiple variables. For example:

In this example, we are trying to retrieve the value of the username parameter from the $_GET array. If it is null or does not exist, we try to retrieve the value from the $_POST array. If this value is also null or does not exist, the value ‘Guest’ is assigned to $username .

The null coalescing operator is particularly useful when dealing with arrays or objects. Here’s an example:

In this example, we are trying to retrieve the value of the age key from the $person array. However, this key has a value of null. Using the null coalescing operator, we can assign the value ‘Unknown’ to the $age variable instead of null.

Moreover, it also can work with functions. For example:

In this example, we are calling the getUserName() function, which returns null. Using the null coalescing operator, we assign the value ‘Guest’ to $username instead of null.

Let’s summarize it.

Wrapping UP

The PHP 7 null coalescing operator streamlines the handling of default values for variables that may be null. Its concise and readable syntax simplifies the code, eliminating the need for verbose ternary expressions.

The operator, denoted by ?? , efficiently deals with situations where a variable may be null or unset, providing a default value if needed. The basic syntax involves checking a variable ( $variable ) and using a default value ( $default ) if the variable is null.

The operator proves beneficial in scenarios such as user input, configuration settings, or any case where a variable might be null, requiring a default value. Its single-line execution enhances code readability and conciseness, offering an alternative to traditional conditional statements.

Further exploration of the null coalescing operator includes chaining for multiple variables and its application with arrays, objects, and functions. Examples demonstrate its versatility, whether handling array elements, object properties, or function returns.

Did you find this article helpful?

 width=

Sorry about that. How can we improve it ?

  • Facebook -->
  • Twitter -->
  • Linked In -->
  • Install PHP
  • Hello World
  • PHP Constant
  • PHP Comments

PHP Functions

  • Parameters and Arguments
  • Anonymous Functions
  • Variable Function
  • Arrow Functions
  • Variadic Functions
  • Named Arguments
  • Callable Vs Callback
  • Variable Scope

Control Structures

  • If-else Block
  • Break Statement

PHP Operators

  • Operator Precedence
  • PHP Arithmetic Operators
  • Assignment Operators
  • PHP Bitwise Operators
  • PHP Comparison Operators
  • PHP Increment and Decrement Operator
  • PHP Logical Operators
  • PHP String Operators
  • Array Operators
  • Conditional Operators
  • Ternary Operator
  • PHP Enumerable
  • PHP NOT Operator
  • PHP OR Operator
  • PHP Spaceship Operator
  • AND Operator
  • Exclusive OR
  • Spread Operator

Data Format and Types

  • PHP Data Types
  • PHP Type Juggling
  • PHP Type Casting
  • PHP strict_types
  • Type Hinting
  • PHP Boolean Type
  • PHP Iterable
  • PHP Resource
  • Associative Arrays
  • Multidimensional Array

String and Patterns

  • Remove the Last Char
  • Getting started with PHP
  • Awesome Book
  • Awesome Community
  • Awesome Course
  • Awesome Tutorial
  • Awesome YouTube
  • Alternative Syntax for Control Structures
  • Array iteration
  • Asynchronous programming
  • Autoloading Primer
  • BC Math (Binary Calculator)
  • Classes and Objects
  • Coding Conventions
  • Command Line Interface (CLI)
  • Common Errors
  • Compilation of Errors and Warnings
  • Compile PHP Extensions
  • Composer Dependency Manager
  • Contributing to the PHP Core
  • Contributing to the PHP Manual
  • Control Structures
  • Create PDF files in PHP
  • Cryptography
  • Datetime Class
  • Dependency Injection
  • Design Patterns
  • Docker deployment
  • Exception Handling and Error Reporting
  • Executing Upon an Array
  • File handling
  • Filters & Filter Functions
  • Functional Programming
  • Headers Manipulation
  • How to break down an URL
  • How to Detect Client IP Address
  • HTTP Authentication
  • Image Processing with GD
  • Installing a PHP environment on Windows
  • Installing on Linux/Unix Environments
  • Localization
  • Machine learning
  • Magic Constants
  • Magic Methods
  • Manipulating an Array
  • Multi Threading Extension
  • Multiprocessing
  • Object Serialization
  • Altering operator precedence (with parentheses)
  • Association
  • Basic Assignment (=)
  • Bitwise Operators
  • Combined Assignment (+= etc)
  • Comparison Operators
  • Execution Operator (``)
  • Incrementing (++) and Decrementing Operators (--)
  • instanceof (type operator)
  • Logical Operators (&&/AND and ||/OR)
  • Null Coalescing Operator (??)
  • Object and Class Operators
  • Spaceship Operator ( )
  • String Operators (. and .=)
  • Ternary Operator (?:)
  • Output Buffering
  • Outputting the Value of a Variable
  • Parsing HTML
  • Password Hashing Functions
  • Performance
  • PHP Built in server
  • php mysqli affected rows returns 0 when it should return a positive integer
  • Processing Multiple Arrays Together
  • Reading Request Data
  • Regular Expressions (regexp/PCRE)
  • Secure Remeber Me
  • Sending Email
  • Serialization
  • SOAP Client
  • SOAP Server
  • SPL data structures
  • String formatting
  • String Parsing
  • Superglobal Variables PHP
  • Type hinting
  • Type juggling and Non-Strict Comparison Issues
  • Unicode Support in PHP
  • Unit Testing
  • Using cURL in PHP
  • Using MongoDB
  • Using Redis with PHP
  • Using SQLSRV
  • Variable Scope
  • Working with Dates and Time
  • YAML in PHP

PHP Operators Null Coalescing Operator (??)

Fastest entity framework extensions.

Null coalescing is a new operator introduced in PHP 7. This operator returns its first operand if it is set and not NULL . Otherwise it will return its second operand.

The following example:

is equivalent to both:

This operator can also be chained (with right-associative semantics):

which is an equivalent to:

Note: When using coalescing operator on string concatenation dont forget to use parentheses ()

This will output John only, and if its $firstName is null and $lastName is Doe it will output Unknown Doe . In order to output John Doe , we must use parentheses like this.

This will output John Doe instead of John only.

Got any PHP Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

PHP 7 Tutorial

  • PHP 7 Tutorial
  • PHP 7 - Home
  • PHP 7 - Introduction
  • PHP 7 - Performance
  • PHP 7 - Environment Setup
  • PHP 7 - Scalar Type Declarations
  • PHP 7 - Return Type Declarations

PHP 7 - Null Coalescing Operator

  • PHP 7 - Spaceship Operator
  • PHP 7 - Constant Arrays
  • PHP 7 - Anonymous Classes
  • PHP 7 - Closure::call()
  • PHP 7 - Filtered unserialize()
  • PHP 7 - IntlChar
  • PHP 7 - CSPRNG
  • PHP 7 - Expectations
  • PHP 7 - use Statement
  • PHP 7 - Error Handling
  • PHP 7 - Integer Division
  • PHP 7 - Session Options
  • PHP 7 - Deprecated Features
  • PHP 7 - Removed Extensions & SAPIs
  • PHP 7 Useful Resources
  • PHP 7 - Quick Guide
  • PHP 7 - Useful Resources
  • PHP 7 - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

It produces the following browser output −

Amit Merchant Verified ($10/year for the domain)

A blog on PHP, JavaScript, and more

Null coalescing assignment operator in PHP

May 4, 2020 · PHP

When PHP 7.0 released , it has added many nice things in PHP’s toolbelt of utilities. One of the things among this was Null coalescing assignment operator (??) .

So basically, the operator can be used for the scenarios where you need to check if the variable is set or not before assigning it to an another variable. For instance, check the following code which you might be writing pre PHP 7.0 era.

The above code code can be reduced to following in PHP 7.0 by using null coalescing assignment operator like so.

Essentially, the null coalescing assignment operator returns its first operand if it exists and is not NULL ; otherwise it returns its second operand.

You can further make it more tidier by writing it as short-hand version like so.

As you can see in the example above, it’s now matter of just one line when you need to accomplish something like above. Looks pretty neat and clean, no?

PHP 8 in a Nutshell book cover

» Share: Twitter , Facebook , Hacker News

Like this article? Consider leaving a

Caricature of Amit Merchant sketched by a friend

👋 Hi there! I'm Amit . I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

More on similar topics

Property hooks are coming in PHP 8.4

How to return multi-line JavaScript code from PHP

What's new in PHP 8.4

Tools to make your developer experience better in PHP

Awesome Sponsors

Download my eBook

PHP 8 in a Nutshell

Recommendation(s)

Get the latest articles delivered right to your inbox!

No spam guaranteed.

Follow me everywhere

More in "PHP"

Using Google's Gemini AI in PHP

Recently Published

Property hooks are coming in PHP 8.4 NEW

A free alternative to GitHub Copilot

Talk to websites and PDFs with this free Chrome Extension

RunJS — A JavaScript Playground on your desktop

The fluent data helper in Laravel

Top Categories

Nullish coalescing

What about default assignment while destructuring #, mixing and matching operators #, tell me about document.all #, support for nullish coalescing #.

  • Web Development

What's the Difference Between ?? and ?: in PHP?

  • Daniyal Hamid
  • 06 Jun, 2021

?: (Elvis Operator)

The elvis operator ( ?: ) is actually a name used for shorthand ternary (which was introduced in PHP 5.3). It has the following syntax:

This is equivalent to:

?? (Null Coalescing Operator)

The null coalescing operator ( ?? ) was introduced in PHP 7, and it has the following syntax:

The table below shows a side-by-side comparison of the two operators against a given expression:

This post was published 14 May, 2018 (and was last revised 06 Jun, 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 .

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Nullish coalescing assignment (??=)

The nullish coalescing assignment ( ??= ) operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish ( null or undefined ).

Description

Nullish coalescing assignment short-circuits , meaning that x ??= y is equivalent to x ?? (x = y) , except that the expression x is only evaluated once.

No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :

Neither would the following trigger the setter:

In fact, if x is not nullish, y is not evaluated at all.

Using nullish coalescing assignment

You can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and default values , ??= also applies the default value if the property has value null .

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Nullish coalescing operator ( ?? )

DEV Community

DEV Community

Thomas Scharke

Posted on Mar 29, 2021

Nullish coalescing operator - explained

The Nullish coalescing operator is a new and additional JavaScript operator that has been available since June 2020 with ECMAScript 2020 (ES2020) of the programming language.

In addition to the well-known binary logical operators && (AND) and || (OR), it is the third operator non-binary and has the notation ?? .

It's always used when I want to explicitly check whether the value of a variable is available to use or, if the value is not available, to continue working with another value.

Here is the "classic" for me: Once with an if block, then in a "simplified" notation with the OR operator and last but not least in the notation with the new Nullish coalescing operator .

The first simplification, with the OR operator , works in most cases, but does not cover the case of working with boolean values.

But let's go through it step by step and see why the variants with the OR-operator work and then switch to the usually "better" Nullish coalescing operator .

OR-Operator

The binary logical operator ( Binary Logical Operator ) || (OR) is defined as follows:

{expression left side} || {expression right side}

I.e. if the expression on the left side delivers the value false the expression on the right side is interpreted, otherwise the expression on the left side is interpreted.

For our "simplification" from above...

It means that if the variable firstValue returns the value true , this value is returned (and in this case assigned to the variable secondValue ). However, if the variable firstValue returns false , the value of the right side is assigned to the variable secondValue - in my case the value DEFAULT_VALUE .

Step by step

Let's go through my example above step by step and see what I mean by...

and how the Nullish coalescing operator helps us here.

To do this, I put my example into a function and then execute it:

🥳 Everything works fine and the code also works with boolean values. 🥳

Reflexively, I feel like "simplifying" this code and using the possibilities of JavaScript for myself. Because I can determine that a value exists with an if (firstValue) , which leads to this version of my code:

😮 Oops...When I pass a false to the function I get back the value DEFAULT_VALUE and not the value false as expected 🤔

I go one step further and "simplify" my code again; and this time I use the OR operator :

I find the last "simplification" of my code even better. It takes away the if block and makes the code easier to read.

But both "simplifications" lead to the same unexpected result when I call the function with the value false .

What have I broken? 🤔

I haven't broken anything. I merely used, in both simplifications, the functionality of JavaScript that assumes that a value must be false ( false ) - that is, falsy . In the concrete case, with my if block and the OR operator , I check whether the value firstValue is false and then use the value DEFAULT_VALUE .

When is a value "falsy"

In JavaScript, a value is ( false ) or falsy if it is null , undefined , 0 or false .

And since this is the way it is in JavaScript, I have also changed the behaviour of my implementation with my "simplification" of the code 🤷.

Call the last two code examples with 0 (Zero):

Again, I want the value 0 (Zero) to be returned, but I get - logically - the value DEFAULT_VALUE 🤷

Let's get back to the actual implementation with the following expression in the if block:

From this derives my requirement that I want to check whether a value is nullish and not whether a value is falsy , as I have (unwittingly) done through my "simplifications".

What does nullish mean

With nullish it's meant that an expression must have the values null or undefined , only then it is nullish .

And exactly this is and was what I wanted to have with my first implementation and have implemented.

Can I not now "simplify" my introductory example? Do I have to manually query all nullish values in JavaScript myself?

😱😱😱 N O O O O 😱😱😱

The new one - Nullish coalescing operator ( ?? )

This is where the new one comes into play - the third logical operator in JavaScript.

Ladies and gentlemen the Nullish coalescing operator 🚀🚀🚀, which is written in JavaScript as ?? and is defined as follows:

{expression left side} ?? {expression right side}

This operator behaves similarly to the OR operator , but with the crucial difference...

It checks if the expression on the left side is "nullish" .

And not, as with the OR operator , whether the expression is false .

A few examples of the Nullish coalescing operator :

And with this knowledge, I can also "simplify" my code example again - like this...

I have one more...

In my examples with the Nullish coalescing operator you will have noticed that calling my "simplified" functions with an empty string ( "" ) does not result in DEFAULT_VALUE being returned.

This is not relevant to the way my example works, but I don't want to hide from you why this happens.

The answer is obvious: The nullish coalescing operator ( ?? ) checks whether a value is nullish , i.e. whether it's null or undefined . And an empty string ( "" ) is an empty string in JavaScript and thus neither null nor undefined - but falsy 🤣

Another example

Let's go one step further and work with boolean values like true and false this time. Let's say, in the context of a configuration that should give a sign of life exactly when we are online and assumes that we are (always) online (by default):

At this point in the text I have now reckoned with the false return value of the last call to the function, but it is not what I wanted.

I want the return value of the function to give me false when we're offline, i.e. when we set the key online in the passed object to false ( { online: false } ).

The known problem

From what I've learned, this wrong result of my function call makes sense. Because online || true has the following values with the last call: false || true .

And if the left side of the OR operator returns false the value of the expression on the right side is used (the value of the left side is falsy ) - in our case true 🤷.

The code works exactly as written, but not as expected.

Possible solutions

For my function that expects a configuration object, I could work with Destructuring and define a default value:

Or, instead of a configuration object, I use a boolean and check it with the strict inequality operator ( !== ):

But in this article the Nullish coalescing operator is the star 🤩 and for my configuration function also a solution:

  • The first version of this article I wrote in my native language because there is a very active German JavaScript Community of which I am a part and which I would like to give something back to 🙇
  • Or to say it with the hashtag of my trainer buddy WebDave : #CommunityRocks and in this case #GermanJavaScriptCommunityRocksToo 😉🚀😎

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

arichy profile image

A common TypeScript error with useRef

Arc - Apr 15

giuliano1993 profile image

Rivet - JS, AI and the agent builder we deserve

Giuliano1993 - Apr 15

techtobe101 profile image

Jenkins CI/CD Freestyle Project: A Comprehensive Guide

Tech Tobé - Apr 16

slobodan4nista profile image

The Compounded Interest of Good Software: An example of Carousel Components

Slobi - Apr 15

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

IMAGES

  1. Learn JavaScript Nullish Coalescing Operator & Assignment in 10 Minutes

    php nullish assignment

  2. PHP is_null()

    php nullish assignment

  3. Learn PHP: NULL

    php nullish assignment

  4. Why is PHPStorm not able to understand nullish coalescing operator in

    php nullish assignment

  5. PHP Tutorial For Beginners 16

    php nullish assignment

  6. PHP Null Data Type

    php nullish assignment

VIDEO

  1. JavaScript'te Fonksiyonlarda Varsayılan Parametre Değerleri

  2. How to use the nullish operator in Javascript

  3. Nullish Coalescing Operator

  4. Nullish coalescing operator do Javascript #javascript #programming #python #dev #frontend #fy #java

  5. Nullish coalescing error || this.options = options ?? {}; node nullish coalescing error ||Mongoose

  6. 1. PHP kursiga kirish. PHP haqida.

COMMENTS

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

    Stack Overflow Public questions & answers; Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Talent Build your employer brand ; Advertising Reach developers & technologists worldwide; Labs The future of collective knowledge sharing; About the company

  2. 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.

  3. Null Coalescing Operator in PHP: Embracing Graceful Defaults

    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.

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

    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.

  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. 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 ...

  6. PHP null coalescing operator

    By employing the null coalescing operator, you can quickly set fallback values to ensure your code continues to function seamlessly. To sum it up, the null coalescing operator is an essential tool that simplifies handling null values in PHP. Whether it's handling user input, database records, or API responses, this operator proves to be an ...

  7. PHP 7's Null Coalescing Operator: How and Why You Should Use It

    PHP 7's null coalescing operator is handy shortcut along the lines of the ternary operator. Here's what it is, how to use it and why: Here's what it is, how to use it and why: Ready to learn even more PHP ?

  8. What Is the Null Coalescing Operator (??) in PHP?

    2 years ago. 1 min read. Introduced in PHP 7, the null coalescing operator ( ??) has the following syntax: // PHP 7+. leftExpr ?? rightExpr; Which means that leftExpr is returned when leftExpr exists and is NOT null; otherwise it returns rightExpr. For example, all the following statements are equivalent: // PHP 7+ // using the null coalescing ...

  9. PHP Null Coalescing Operator: Handling Null Values

    The PHP null coalescing operator, denoted by ??, is a convenient feature introduced in PHP 7 that simplifies the way developers handle the default values for variables that may be null.. It provides a concise and readable syntax for dealing with potentially null values without the need for verbose ternary expressions.

  10. PHP Tutorial => Null Coalescing Operator (??)

    Example. Null coalescing is a new operator introduced in PHP 7. This operator returns its first operand if it is set and not NULL.Otherwise it will return its second operand.

  11. PHP 7

    PHP 7 - Null Coalescing Operator - In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

  12. PHP 7

    Jun 9, 2021. Null Coalescing Operator (??) is a new feature of PHP 7.It is usually used to check if a variable has a value. It will be easier for you to understand if you have ever used the "Ternary Operator ??" and isset() function before. If there is no value in the variable, it returns a value by default.

  13. Null coalescing assignment operator in PHP

    Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

  14. Nullish coalescing · V8

    The nullish coalescing proposal ( ??) adds a new short-circuiting operator meant to handle default values. You might already be familiar with the other short-circuiting operators && and ||. Both of these operators handle "truthy" and "falsy" values. Imagine the code sample lhs && rhs. If lhs (read, left-hand side) is falsy, the ...

  15. Assigning NULL to a variable in PHP: what does that do?

    1. A variable could be set to NULL to indicate that it does not contain a value. It makes sense if at some later point in the code the variable is checked for being NULL. A variable might be explicitly set to NULL to release memory used by it. This makes sense if the variable consumes lots of memory (see this question ).

  16. PHP ?? vs. ?:

    php Backend We want to help you create exceptional digital products — explore curated sources for inspiration and time-saving web design, development and digital marketing articles by industry experts.

  17. Mastering Null Safety in PHP 8: A Comprehensive Guide to Using ...

    Welcome to this in-depth article that explores the powerful null safe operator in PHP 8. With the introduction of PHP 8, null safety has become a game-changer in handling null values with ease and…

  18. Nullish coalescing assignment (??=)

    No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :

  19. PHP: Assigning of NULL to variable, TRUE or FALSE ? What is NULL?

    I'm not sure what's unclear. 1: assignment = operator will return result of expression that was assigned to variable after execution.So that's why you'll get your element in an array. 2: second expression in for loop is always treated as boolean expression, therefore, it's result will be checked against true according to PHP's type juggling. That's why you'll get that for condition will break ...

  20. Nullish coalescing operator

    The first simplification, with the OR operator, works in most cases, but does not cover the case of working with boolean values.. But let's go through it step by step and see why the variants with the OR-operator work and then switch to the usually "better" Nullish coalescing operator.. OR-Operator The binary logical operator (Binary Logical Operator) || (OR) is defined as follows:

  21. PHP

    PHP - assignment by reference with null coalescing operator. Related. 1. Null coalescing operator also usable with falsy values, but not nulls? 13. Null coalesce operator with casting. 1. Repeated Variable at PHP 7 Null Coalescing operator. 3. PHP non-falsy null coalesce operator. 2.