Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?
The ternary operator (? :) in PHP provides a compact way to write simple if-else statements in a single line. It evaluates a condition and returns one of two values based on whether the condition is true or false.
Syntax
The basic syntax of the ternary operator is −
$variable = condition ? value_if_true : value_if_false;
Basic Example
Here's how to use the ternary operator to check if a value meets a condition ?
<?php
$value = 100;
$result = $value >= 100 ? "Greater Than or Equal to 100" : "Less Than 100";
echo $result;
?>
Greater Than or Equal to 100
Comparison with If-Else
The ternary operator is equivalent to a traditional if-else statement but more concise −
<?php
$score = 85;
// Using ternary operator
$grade = $score >= 90 ? "A" : ($score >= 80 ? "B" : "C");
echo "Ternary: " . $grade . "<br>";
// Equivalent if-else statement
if ($score >= 90) {
$grade2 = "A";
} elseif ($score >= 80) {
$grade2 = "B";
} else {
$grade2 = "C";
}
echo "If-else: " . $grade2;
?>
Ternary: B If-else: B
Nested Ternary Operators
You can nest ternary operators for multiple conditions, though readability may decrease −
<?php
$age = 25;
$category = $age < 18 ? "Minor" : ($age < 65 ? "Adult" : "Senior");
echo "Age category: " . $category;
?>
Age category: Adult
Conclusion
The ternary operator is perfect for simple conditional assignments and makes code more concise. However, use it judiciously − for complex conditions, traditional if-else statements are more readable.
