DEV Community

Odunayo Ogungbure
Odunayo Ogungbure

Posted on

Shorthand Conditionals in PHP You Should Know

The if...else statement is one of the most common logic patterns we write as programmers. It executes one block of code if a condition is true, and another if the condition is false. It’s so fundamental that I honestly can’t remember a day I didn’t write some form of if condition.

As a quick refresher, here’s what the basic syntax looks like:

if (condition) {
    // code to execute if condition is true
} else {
    // code to execute if condition is false
}
Enter fullscreen mode Exit fullscreen mode

Imagine you’re building an e-commerce backend. When a user makes a payment, you want to handle scenarios where the payment is successful or fails:

if ($payment->isSuccessful()) {
    // Mark order as paid
    // Generate invoice
    // Update user’s purchase history
    // Send confirmation email
} else {
    // Log the failure
    // Notify the user
}
Enter fullscreen mode Exit fullscreen mode

In the example above, both the success and failure paths include multiple steps. This is where the traditional if...else syntax shines; it keeps your logic clean, organised, and easy to maintain.

But sometimes, our logic isn’t that complex. For instance, what if we simply want to check if a user's role is "admin"? If it is, they can access a page; if not, they can’t. Writing the traditional if...else block for this might seem too much.

Luckily, PHP provides shorthand techniques for conditional logic that can keep your code concise and readable.

In this article, we’ll explore some of these shorthand methods and when best to use them.


1. Ternary Operator

This is probably the most well-known shorthand for conditionals, and chances are, you've already seen it in the wild.

$value = (condition) ? 'return this if true' : 'return this if false';
Enter fullscreen mode Exit fullscreen mode

This would normally be a 4–5 line traditional if...else block, but now it is just a single line. It’s great for simple decisions where both outcomes are straightforward.

$score = 70;
$result = ($score >= 70) ? 'pass' : 'fail';
Enter fullscreen mode Exit fullscreen mode

Nesting Ternary Operators

You can nest ternary operators, but here’s a big disclaimer: I don’t recommend it. It quickly becomes unreadable and error-prone. It’s usually better to stick to the traditional if...else block.

$value = ($user->isAdmin())
    ? 'Show admin panel'
    : ($user->isEditor() ? 'Show editor dashboard' : 'Show viewer homepage');
Enter fullscreen mode Exit fullscreen mode

Yes, it works—but imagine debugging this later 😅

2. Elvis Operator (Short Ternary)

You might wonder why it's called "Elvis." Got no idea 🤷🏾‍♂️.

The Elvis operator is a shortened version of the ternary operator where the middle part is omitted. It returns the condition if it's truthy, or a fallback value if not.

$displayName = ($name) ? $name : 'Guest';  // Regular ternary
$displayName = $name ?: 'Guest';          // Elvis shorthand
Enter fullscreen mode Exit fullscreen mode

3. Null Coalescing Operator (??)

Ever had to do an isset() check before using a value?

$email = isset($_POST['email']) ? $_POST['email'] : '';
Enter fullscreen mode Exit fullscreen mode

With the null coalescing operator (??), it becomes much cleaner:

$email = $_POST['email'] ?? 'fallback value';
Enter fullscreen mode Exit fullscreen mode

What it does is check if the left-hand side is set and not null. If it is, that value is returned. Otherwise, the right-hand side is returned.

var_dump($a ?? 'fallback') // 'fallback';
var_dump($a['yt'] ?? 'fallback') // 'fallback';
var_dump(null ?? 'fallback') // 'fallback';
var_dump(false ?? 'fallback') // false;
var_dump(true ?? 'fallback'); // true
var_dump('' ?? 'fallback'); // ''
var_dump(0 ?? 'fallback'); // 0
Enter fullscreen mode Exit fullscreen mode

This operator is also super useful for nested data, like accessing array keys or object properties without a ton of isset() checks:

$user['bio']['address'] ?? '-';
$user->bio->address ?? '-';
Enter fullscreen mode Exit fullscreen mode

You can even set defaults in one step using the null coalescing assignment (??=), available in PHP 7.4+:

$_POST['user'] ??= 'Guest';
Enter fullscreen mode Exit fullscreen mode

Which is the same as:

$_POST['user'] = $_POST['user'] ?? 'Guest';
Enter fullscreen mode Exit fullscreen mode

4. Spaceship Operator (<=>)

This one isn’t used every day, but it's good to know.

The spaceship operator is also called the three-way comparison operator. It compares two values and returns:

  • -1 if the left side is less than the right
  • 0 if they are equal
  • 1 if the left side is greater
echo 5 <=> 10;  // -1
echo 10 <=> 10; // 0
echo 15 <=> 10; // 1
Enter fullscreen mode Exit fullscreen mode

It can be used with numbers, strings, arrays, and even objects (if properly implemented). It’s useful when writing custom sorting logic.

Final Thoughts

PHP’s shorthand comparison can help reduce the amount of boilerplate code and keep things concise, but always remember: readability matters. Just because you can write a fancy one-liner doesn’t mean you should. Use shorthand where it makes sense, and fall back to the traditional if...else when the logic gets too layered or complex.

Sometimes, writing it the long way is the smart way.

Top comments (0)