PHP - Ternary Operator

The ternary operator is a shorter version of an if...else expression. It allows us to execute an expression if a condition is satisfied and another expression if the condition is not satisfied.

The ternary operator can be used to replace certain types of if...else statements. It’s more regularly used with simple conditions. Using with multiple conditions comprises with readability.

It’s one of the most used operator, as it replaces the complete block of the if...else statement with just simple as a single line.

Ternary Operator in PHP

In this article, you will learn about the ternary operator and its use in PHP; explained with the help of examples.

Ternary Operator
Ternary Operator

Syntax

booleanExpression ? expression1 : expression2;

Here, booleanExpression is evaluated and

  • A booleanExpression evaluates to either true or false.
  • If the resultant value of booleanExpression is true, expression1 will be executed.
  • And, if the resultant value of booleanExpression is false, expression2 will be executed.
  • As the name suggests, it accepts 3 operands (booleanExpression, expression1, and expression2). Hence, the name ternary operator.

Example to identify whether number is zero or non-zero:

$num = 12;

echo $num === 0 ? 'Zero' : 'Non-zero';

// Output
// Non-zero

Example to find the largest number of two numbers

$a = 12;
$b = 24;

echo $a === $b
  ? 'Both numbers are same'
  : ($a > $b ? 'A is larger than B' : 'B is larger than A');

// Output
// B is larger than A
  • The above code for ternary operator includes condition($a === $b) for same value in both variables, next condition($a > $b) to identify larger of $a & $b.
  • Some developers might prefer this way but it might be confusing for beginners.
  • Adding more conditions in the ternary operator will cost its readability.

Note: Conditions can also include the use of Logical operators(&&, ||, !)

The syntax for a ternary operator is shorter than an if...else statement, and sometimes it might make more sense to use it.

Hope you like this!

Keep helping and happy 😄 coding

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳