Simplify Null Checks with PHP 8.0's Shorthand

Simplify Null Checks with PHP 8.0's Shorthand

Oct 4, 2023 - 05:22
Oct 4, 2023 - 05:26
 0  62

Suppose you have a situation where you want to check if a user's profile has a country, a state, and a city. If any of them are missing, you want to provide default values. Without the shorthand, it could involve nested if statements like this:

In the above code, the shorthand null coalescing operator (??) is used to check if each part of the location (country, state, and city) exists in the user's profile. If any of them are missing or null, it defaults to the appropriate default value. This approach significantly reduces the nesting levels and makes the code more concise and easier to read.

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow