Mastering Ternary Operator in PHP

Updated: January 9, 2024 By: Guest Contributor Post a comment

Introduction

The ternary operator in PHP provides a shorthand way of writing conditional statements, allowing for clearer and more concise code. In this tutorial, we’ll explore how to use the ternary operator through a series of examples from simple to complex scenarios.

Basic Usage of Ternary Operator

The ternary operator is a conditional operator that takes three operands. The basic syntax is (condition) ? (expression_if_true) : (expression_if_false). Here’s a simple example:

$age = 20;
$message = ($age >= 18) ? 'You are an adult.' : 'You are not an adult.';
echo $message;

This will output You are an adult. since the condition $age >= 18 is true.

Nested Ternary Operators

Nested ternary operators allow for multiple conditions to be checked in a single statement. Care should be taken to ensure readability:

$age = 20;
$message = ($age >= 18) ? (($age >= 65) ? 'You are a senior.' : 'You are an adult.') : 'You are not an adult.';
echo $message;

The above code outputs You are an adult., since the first condition is true, and the nested condition is false.

Using with Functions

The ternary operator can be used to execute different functions based on a condition. For example:

function is_even($num) {
    return $num % 2 === 0;
}

function is_odd($num) {
    return !is_even($num);
}

$number = 5;
$result = is_even($number) ? 'Even number' : 'Odd number';
echo $result;

This will output Odd number since the number 5 is odd.

Ternary Operator as a Null Coalescing Operation

PHP 7 introduced the null coalescing operator ??, but a similar effect can be achieved with the ternary operator by using isset():

$username = isset($_GET['username']) ? $_GET['username'] : 'guest';
echo 'Welcome ' . $username;

This will output Welcome guest if the username is not provided in the query string, otherwise it outputs the username.

Ternary Operator for Shortening Lengthy If-Else Chains

You can replace lengthy if-else chains with the ternary operator. However, maintaining readability should always be a priority:

$score = 85;
$grade = ($score >= 90) ? 'A' : (($score >= 80) ? 'B' : (($score >= 70) ? 'C' : (($score >= 60) ? 'D' : 'F')));
echo 'You got a ' . $grade;

With a score of 85, this code will output You got a B.

Advanced Conditional Assignment

In more advanced use-cases, the ternary operator can handle compound conditions and execute corresponding complex expressions:

$login_attempts = 3;
$account_locked = ($login_attempts > 5) ? true : false;
$message = ($account_locked) ? 'Your account is locked.' : 'You have ' . (5 - $login_attempts) . ' attempts remaining.';
echo $message;

If login attempts exceed 5, the account is locked. Otherwise, it shows how many attempts are remaining.

Best Practices with Ternary Operator

It’s essential to avoid overusing ternary operators as they can significantly decrease readability. Picking the right scenario to use a ternary operator can greatly improve the clarity and efficiency of your code.

Conclusion

The ternary operator in PHP is a powerful tool for writing concise and readable conditional statements. Throughout this tutorial, we’ve explored its use across various scenarios, illustrating how to effectively use it to streamline your PHP code. Remember that readability should always come first, so use ternary operators wisely.