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;
Top comments (1)
Php has an interesting feature of the ternary operator - a specific and unique order of execution.
I have known about this interesting nuance for a long time, but just yesterday I discovered an error in one of the open sources: the author clearly did not know about this nuance and was caught. Therefore, this article is only a warning. After all, if a programmer expects the same behavior from php as from other languages, he can get into halepa.
This technique is very convenient for setting values, depending on the conditions. A neat replacement for if-else. For example:
in the official manual:
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2