Table of Content
The PHP ternary operator gives you a way to write short expressions. It reduces lines of code and avoids long if-else blocks. Also, it improves readability in simple checks.
What Is the PHP Ternary Operator?
The PHP ternary operator acts like a shortcut for if-else. It checks a condition and returns one value if true.
It returns another if false. You use it in expressions because it keeps the code compact and improves readability for short checks. Also, it avoids large blocks for simple choices.
The syntax looks like this.
condition ? value_if_true : value_if_false;You write the condition first. PHP evaluates it. It returns the value after the question mark if true and returns the value after the colon if false. This pattern keeps the expression’s logic clear in one line.
The ternary operator returns one value. You can assign it to a variable or use it directly in expressions.
PHP checks the condition. It returns one value if the condition has a true result. It returns another value if the result is false and avoids multiple lines for if-else.
Here is an example:
$age = 18;
$status = ($age >= 18) ? 'Adult' : 'Minor';This assigns ‘Adult’ if $age is 18 or more. It assigns ‘Minor’ if not.
Use the ternary operator to make simple choices. You write it in assignments and in function arguments. Also, you use it in return statements. It shortens code without losing clarity.
You can assign values in one line.
$isLoggedIn = true;
$user = $isLoggedIn ? 'Welcome User' : 'Guest';This assigns ‘Welcome User’ if $isLoggedIn is true. It assigns ‘Guest’ if false.
Here are alternative syntaxes in PHP 7+:
- Null Coalescing Operator
?? - Short Ternary
?:
Nested Ternary Operators
You can write nested ternary operators. Use them to choose from more than two options. Read them carefully. Break them into clear levels.
Here’s the breakdown step-by-step.
PHP checks the first condition. If true, it returns the first value. If false, it evaluates the next ternary. You keep nesting for more choices. Avoid too many levels. It becomes hard to read.
For example:
$score = 85;
$grade = ($score >= 90) ? 'A' : (($score >= 80) ? 'B' : 'C');This assigns ‘A’ for scores of 90 or more. It assigns ‘B’ for scores 80 to 89. It assigns ‘C’ for less than 80.
Here is another example:
$age = 16;
$result = ($age >= 18) ? 'Adult' : (($age >= 13) ? 'Teen' : 'Child');This assigns ‘Adult’ for 18 or more. It assigns ‘Teen’ for 13 to 17. It assigns ‘Child’ for under 13.
The Difference Between the Ternary Operator and the if-else Statement
The ternary operator uses short expressions for simple choices. If-else gives better control for many steps.
Here are the key differences:
| Ternary Operator | If-Else Statement |
|---|---|
| One-line expression | Multi-line control block |
| Best for short checks | Best for complex logic |
| Returns value directly | Executes statements |
Use cases:
- Ternary for simple assignments.
- If-else for multiple steps.
- Ternary in expressions.
- If-else in control flows.
Other shorthand operators exist, like the Elvis operator, Null Coalescing operator, and Short Ternary to simplify your checks in specific use cases.
Use the Ternary Operator in Echo Statements
You can write the ternary inside the echo to choose the output directly without an if-else block.
For example:
$isAdmin = true;
echo $isAdmin ? 'Admin Panel' : 'User Panel';This shows ‘Admin Panel’ if true. It shows ‘User Panel’ if false.
Here is another example:
$stock = 0;
echo $stock > 0 ? 'In Stock' : 'Out of Stock';This displays ‘In Stock’ if stock is positive. It shows ‘Out of Stock’ if not. Avoid it in long conditions. It becomes hard to read. Use if-else for clarity.
Ternary Operator with Arrays and Objects
You can use the ternary operator to choose array elements or object properties. It keeps code short.
For example:
$data = ['name' => 'John'];
$name = isset($data['name']) ? $data['name'] : 'Unknown';The output:
John
Here is another example:
$user = (object)['role' => 'editor'];
$role = isset($user->role) ? $user->role : 'guest';The output:
editor
Wrapping Up
In this article, you learned what the PHP ternary operator is and how it works. Here is a quick recap:
- It shortens the expression that evaluates a condition.
- It uses clear syntax.
- The ternary operator replaces simple if-else blocks.
- It works with variables, echo, arrays, and objects.
FAQs
What does the PHP ternary operator do?
How do I write a ternary in PHP?
Can I nest ternary operators in PHP?
Is ternary faster than if-else in PHP?
What is the short ternary in PHP?
What is the null coalescing operator?
When should I avoid ternary operators?
Similar Reads
In PHP, there are plenty of times when you need to connect with other servers or APIs. That's where the…
The whole world of PHP programming revolves around data, be it numbers, text, or more complicated structures. Each of these…
The OOP constructor initializes an object when it is created in PHP. Understand What a Constructor Is in PHP A…
In web development, managing and manipulating data is one of the most common tasks. When it comes to storing complex…
The PHP object is an instance from the PHP class or the main data structure that is already been created…
Text does not always look the same. One word may appear in lowercase, another in uppercase. You want both to…
PHP foreach loop came to help work with array data in a simple way. Arrays and objects grew more common…
PHP array_intersect_assoc compares values and keys in arrays. It returns matches with the same key and value from all arrays…
The first appearance of PHP iterable was in PHP version ( 7.1 ) – Iterables are a powerful feature in…
In this tutorial, you will learn how to install PHP on your Operating system such as Ubuntu, Windows, or macOS.…