PHP Ternary Operator

The ternary operator is a short way to write a simple if...else statement in one line. It is called ternary because it works with three parts: a condition, a result for true and a result for false.


Syntax

$result = (condition) ? value_if_true : value_if_false;

Example

The same logic written with if-else, and with the ternary operator:

<?php
$age = 20;

// Using if...else
if ($age >= 18) {
    $status = "Adult";
} else {
    $status = "Minor";
}

// Using the ternary operator
$status2 = ($age >= 18) ? "Adult" : "Minor";

echo $status . "<br>";
echo $status2;
?>

Output:

Tutorials Class - Output Window

Adult
Adult

You can use it directly inside echo also.

<?php
$loggedIn = true;

echo $loggedIn ? "Welcome back!" : "Please login.";
?>

Output:

Tutorials Class - Output Window

Welcome back!


Short ternary (?:)

If you leave the middle part, PHP uses the condition value itself when it is true. It is a nice way to set a default for empty values.

<?php
$username = "";

echo $username ?: "Guest";
?>

Output:

Tutorials Class - Output Window

Guest


Null coalescing operator (??)

The ?? operator returns the left value if it exists and is not NULL. It does not give a warning for undefined variables or array keys.

<?php
$user = ["name" => "Robin"];

echo $user["city"] ?? "Not given";
?>

Output:

Tutorials Class - Output Window

Not given

The difference between ?: and ?? is: ?: checks if a value is false-like (0, empty string), and ?? checks only if the value is not set or NULL. Learn more in the ?? operator.


Nested ternary

You can put one ternary inside another, but it is hard to read. Since PHP 8, a nested ternary without brackets gives an error, so you must use brackets.

<?php
$marks = 82;

echo $marks >= 90 ? "A" : ($marks >= 75 ? "B" : "C");
?>

Output:

Tutorials Class - Output Window

B

Note: Use the ternary operator only for short and simple conditions. For long or nested conditions an if-elseif or a match expression is easier to read. Read What is the use of the ternary operator? also.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.