PHP Ternary Operator

Emmanuel Gautier / October 31, 2014

The usage of the ternary operator is not the simplest and the most readable way to develop but can be useful for simple conditions. The implementation of the ternary operator depends on the language, let's see how to do it in PHP.

What is the ternary operator?

It is a one line way to write some conditions like the following example:

if($boolean) {
  echo "foo";
} else {
  echo "bar";

This condition is simple but takes 5 lines of code. The ternary operator allows to have this condition in only one line without removing too much readability here:

echo ($boolean ? "foo" : "bar");

You write your code like this for every use case and have a ternary operator into a ternary operator. But this way can lower the readability of your code, so making the application harder to understand and to maintain:

echo ($boolean ? ($boolean2 ? "true true" : "true false") : "false");

The ternary operator could be write as following as well:

$value = $value ?: $othervalue;

This way could be useful to assign a default value. Let's take as an example one use case where we want to display as name, the family name if exists else the username :

$display_name = $lastname ?: $username;


Related Posts