Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

IF-Else: Ternary and Null Safe Operators

Premium
3 min read

When building applications, performing comparisons is very common. Recent PHP versions improved the good old "if-else" with a few shorter syntax options.


Ternary Operator: "? ... :"

The ternary operator is used to shorten the if/else.

Instead of writing this:

if (request()->has('customer_id')) {
return request()->get('customer_id');
} else {
return null;
}

You can write this:

request()->has('customer_id') ? request()->get('customer_id') : null

This ternary operator can be shortened using the "Elvis" "?:" operator.

request()->get('customer_id') ?: null

In this case, the returned value will be from the request or null.


Null coalescing: "??"

The null coalescing operator has been...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…