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;
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.
Featured Posts
Introducing new blog about OAuth, OpenID Connect, and IAM Solutions
I'm excited to announce the launch of a new blog named CerberAuth, where I'll be exploring the world of OAuth, OpenID Connect, and IAM solutions for modern security.
How to deal with Docker Hub rate limit on AWS
Since 2020, DockerHub has been limited to only 200 container image pull requests per six hours. This article will help you to deal with this limitation on AWS.
How to enable Python type checking in VSCode
Python now has support for type hints. In this article, we will see how to enable better IntelliSense and type checking analysis in VSCode.