Skip to main content

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? (30 h 41 min)

You also get:

55 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…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.