Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 21 / 68

Writing Null-Safe Code (the ?? operator)

In this lesson you will learn null-safe code in PHP with the ?? operator, so missing data can be handled safely. This is for anyone searching for "PHP null-coalescing operator how to use".

?? (the null-coalescing operator) uses the right-hand value only when the left is null or undefined. Since reaching for a missing array key raises a warning, this operator is how you supply a safe fallback.

The sample code prints a replacement string with ?? "No address set" when $user["address"] is null. See how convenient it is to write safe code without checking isset() every time data might be missing.

A common stumbling block for beginners is the difference between ?? and ||. || switches to the right side even for falsy values such as 0 or an empty string, while ?? only does so for null or undefined. In a case like "show 0 when the score is zero", using anything but ?? gives the wrong result.

There is also a ??= assignment operator that assigns only when the variable is undefined. Data arriving from an API with some fields missing is common, which makes this a very heavily used operator.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)