This short tutorial will introduce you to PHP's ternary conditional operator. Whether you've been programming for a long time or just getting started, the ternary operator is a very handy trick to know. However, many programmers don't use this because it looks so confusing. But hopefully this tutorial will help clear up any confusion.
What exactly is a ternary conditional operator?
Basically, it's a very shortened form of an if/else statement.
Let's look at an example if/else that could be turned into a ternary form:
- Code: Select all
<?php
$my_color = 'green';
if ($my_color == 'green')
{
print 'My favorite color is green.';
}
else
{
print 'My favorite color is ' . $my_color;
}
?>
All of that could be succinctly rewritten as:
- Code: Select all
<?php
$my_color = 'green';
( $my_color == 'green' ) ? print 'My favorite color is green.' : print 'My favorite color is ' . $my_color;
?>
The basic form of the ternary operator is this:
- Code: Select all
( condition ) ? true_part : false_part
The condition is the same condition you'd use in a if() statement; the true_part is the what you'd put to execute is an if() is true; and the false_part is what you'd put in the else part of a statement.
One other thing we'll look at.
The ternary operator can also assign variables too.
Look at this code:
- Code: Select all
<?php
$my_color = 'green';
$message = '';
if ($my_color == 'green')
{
$message = 'My favorite color is green.';
}
else
{
$message = 'My favorite color is ' . $my_color;
}
?>
That could also be rewritten as:
- Code: Select all
<?php
$my_color = 'green';
$message = ($my_color == 'green') ? 'My favorite color is green.' : 'My favorite color is ' . $my_color;
print $message;
?>
The ternary operator is ideal for shorter if/else statements like the examples above and will save you typing out longer statements. Also using it will make your code cleaner and more readable which should be the goal of all programmers.



