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 on 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.
MySQL Docker Image for Mac ARM M1
MySQL official Docker image is not available for Apple ARM-based M1 and M2 CPUs. But there is some options to use mysql image on Mac and more globally on ARMv8 microarchitecture.
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.