PHP Ternary Operator

Emmanuel Gautier / October 31, 2014

2 min read

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;

Documentation

Consulting

If you're seeking solutions to a problem or need expert advice, I'm here to help! Don't hesitate to book a call with me for a consulting session. Let's discuss your situation and find the best solution together.

Share this post
Follow the RSS feed