Home > Tips & Tricks > Inline if else Condition in PHP – (with double ??)

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 😉

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment