Ternary Operator

This lesson discusses ternary operator using an example.

We'll cover the following

The ternary operator is a comparison operator and it executes different statements based on a condition being true or false.

The ternary operator is shorthand syntax for if-else.

It allows to quickly test a condition and often replaces a multi-line if statement, making your code more compact.

Syntax

Here’s the syntax:

Example

Let’s take a look at an example which uses ternary operators.

Press + to interact
$a=5; #Change values of $a and $b to change output of the code.
$b=2;
($a > $b) ? print "$a is greater than $b" : print "$a is NOT greater than $b";

Explanation

In the code above:

  • The variables $a and $b are set to 5 and 2

  • In line 4, condition ($a > $b) evaluates to true

  • Hence, expression 1 executes and the output dispayed is: 5 is greater than 2

You can try changing the values of $a and $b to 2 and 5.

  • Now expression 2 will execute since the condition will evaluate to false this time as $a will not be greater than $b

  • At the end, the output displayed will be: 2 is NOT greater than 5