Sling Academy
Home/PHP/Mastering Ternary Operator in PHP

Mastering Ternary Operator in PHP

Last updated: January 09, 2024

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.

Next Article: Understanding NULL in PHP

Previous Article: Mastering ‘while’ Loops in PHP

Series: Basic PHP Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array