What is the use of the ternary operator in PHP?

The ternary operator is a short way to write a simple if-else statement in one line. The syntax is condition ? value_if_true : value_if_false.

<?php
$age = 20;

$result = ($age >= 18) ? "Adult" : "Minor";

echo $result;
?>

Output:

Tutorials Class - Output Window

Adult

There is also a shorter form ?: (called Elvis operator). It returns the first value if it is not empty, otherwise the second one.

<?php
$username = "";

echo $username ?: "Guest";
?>

Output:

Tutorials Class - Output Window

Guest

Use it only for short and simple conditions. For long conditions a normal if-else is easier to read. More details in PHP Ternary Operator.


Learn more about the similar topics:
Tutorials
PHP Operators
PHP Ternary Operator
Exercises & Assignments
Write a PHP program to add two numbers
Interview Questions & Answers
What is the difference between == and === Operators in PHP?
What are the arithmetic operators in PHP?
What is the use of the ternary operator in PHP?
What is the null coalescing operator (??) in PHP?
What is the difference between division (/) and modulus (%) in PHP?
What is the difference between != and !== in PHP?
What is the difference between $var++ and $var + 1 in PHP?