Inline if else Condition in PHP – (with double ??)

In this trick, I will show you how you can use double ?? operator (also called “null coalescing operator“) to make inline if else condition more clean and useful.

We all know about if else condition in PHP and any other languages. It is for checking the specific condition is true or not. We mostly used if else block statement for many lines of code but on the other hand we used inline if else condition for short lines of code.

We will use the ternary operator (? :) to perform the inline if else condition. It will check if condition (A) is correct then it will return true (B), if it is wrong then it will return false (C). These operators hold the three parts, that’s why it called the ternary operator.

Let’s look at the example:

Did you see the above example of how we used ternary operator for inline if else condition? First, we have checked the variable is empty or not then return the result.

BUT!!!!

Do you know that we can also make the above inline statement shorter? If not then check this trick.

We will use double ?? to make inline statement more easiest and clean. This operator also called the “null coalescing operator”. Let’s see the example.

The above example will also work the same as we did above. You can use this trick for inline if else condition in php.

Being Tricky 😉

About the Author: Aman Mehra

Hey! I'm Aman Mehra and I'm a full-stack developer and have 5+ years of experience. I love coding and help to people with this blog.

Leave a Reply

Your email address will not be published.