When we write PHP, if{...}else{...} is probably the most used Yes, but sometimes, we can use the ternary operation in C, which can reduce the code a lot! This article talks about some of my techniques and things to pay attention to when using ternary operations in PHP development. Coders who need it can refer to it.
Today a netizen posted a question in the group. It’s not difficult, but it may be wrong.
<span>echo</span> <span>$a</span> == 1 ? 'one' : <span>$a</span> == 2 ? 'two' : <span>$a</span> == 3 ? 'three' : <span>$a</span> == 4 ? 'foura' : 'other'<span>; </span><span>echo</span> "\n";
The output result is:
The result is: four
I didn’t understand it at first, but according to my understanding, the logic should be like this:
echo ($a == 1 ? 'one' :
( $a == 2 ? 'two' :
( $a == 3 ? 'three' :
($a == 4 ? 'four' : 'other'))));
The output is: two
Later, under the guidance of kevinG (qq:48474) and referring to the PHP manual, I finally understood that the interpretation of PHP's ternary symbols is from left to right,