Introduction to the use of php ternary operators, php Operators
When we write PHP, it is possible that if {...} else {...} most of them are used, but sometimes we can use the ternary operation in C to reduce the code! This article describes some tips and notes for using ternary computation in php development. For more information about the coders, see.
Today, a netizen posted a question in the group, but it may be wrong.
echo $a == 1 ? 'one' : $a == 2 ? 'two' : $a == 3 ? 'three' : $a == 4 ? 'foura' : 'other'; echo "\n";
The output result is:
<BR>
Result: four
I cannot understand it at first. According to my understanding, the logic is as follows:
Echo ($ a = 1? 'One ':
($ A = 2? 'Two ':
($ A = 3? 'Three ':
($ A = 4? 'Four': 'Other '))));
Output: two
Later, with the help of kevinG (qq: 48474), I read the php manual and finally understood that the interpretation of the php Trielement was from left to right,
<! --? Php
// At first glance, the output below is 'true'
Echo (true? 'True': false? 'T': 'F ');
// However, the actual output of the preceding statement is 'T', because the ternary operators are calculated from left to right.
// The following statements are equivalent to the preceding statements, but they are clearer.
Echo (true? 'True': 'false ')? 'T': 'F ');
So the above can be explained as follows:
Echo (
($ A = 1? 'One ':
$ A = 2 )? 'Two ':
$ A = 3 )? 'Three ':
$ A = 4 )? 'Four': 'Other ');
In fact, this involves type conversion:
$ A = 1 => false => $ a = 2? True => 'two' = true => 'three '= true => 'four'