Courses

PHP for Laravel Developers

IF-Else: Ternary and Null Safe Operators

Summary of this lesson:
- Learn about ternary and null coalescing operators
- Understand null-safe operator usage
- Explore different ways of handling null values
- Examine shorthand comparison techniques

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 16 lessons of this course? (52 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord