This article mainly introduces about the PHP conditional operator encountered a problem and solution, has a certain reference value, now share to everyone, the need for friends can refer to
Today, I encounter a problem with the PHP nested usage condition operator (ternary expressions)
Phenomenon
Let's look at a C code (test.c):
#include <stdio.h>int main () { int x = 1; int shit = x = = 1? : x = = 2? 200:300; printf ("Value of shit:%d\n", shit); return 0;}
Run it after compiling
root$ gcc test.c-o test &&./testshit Value: 100
The answer is expected, because x==1, so 100 is assigned to shit.
But if we rewrite the code above (test.php) with PHP:
<?php$x = 1; $shit = $x = = 1? : $x = = 2 200:300;echo "shit value: $shit \ n";
Execute:
root$ Value of PHP Test.phpshit: 200
We find that the results of the return are different, why is this?
Investigation
The first suspect might be the comparison operator (= =) in PHP and the conditional operator (?:) Priority issues, let's check out the official PHP documentation
= = priority ratio ?: higher (so is the C language), so
$shit = $x = = 1? : $x = = 2? 200:300;
is equivalent to
$shit = ($x = = 1)? : ($x = = 2)? 200:300;
Once again, it is true that it is possible to exclude the possibility that operator precedence is causing the problem.
But in the official documentation, there is an example of the operator's combination of directions :
This is very similar to the phenomenon described above, and the problem should be here. After a review, the following conclusions were obtained:
Conclusion
int x = 1;int Shit = x = = 1? : x = = 2? 200:300;//is equivalent to int shit = x = = 1?: (x = = 2? 200:300);//equivalent to int shit = x = = 1?: (3 00);//100
$x = 1; $shit = $x = = 1? : $x = = 2? 200:300;//equivalent to $shit = ($x = = 1?: $x = = 2)? 200:300;//equivalent to $shit = (100)? 200:300;//200
In combination with the conditional operator in PHP, we cannot achieve the effect of the if-elseif-elseif-else expression by nesting the conditional operator as in C/C + + , unless we enclose the parentheses in the post-dependent subexpression, which can be resolved in this way:
$shit = $x = = 1? : ($x = = 2? 200:300);
However, in the case of more conditional branching, code readability issues (stacked parentheses) occur:
$shit = $x = = 1? : ($x = = 2: ($x = = 3): ... ($x = = 8? 800:900))))));
Because PHP does not stack parentheses in the execution of the results and C + + is inconsistent, and only by the parentheses to change the default binding direction to achieve the desired result, so the PHP document is simply not recommended nested use of conditional operators:
Note:
It is recommended so you avoid "stacking" ternary expressions. PHP ' s
Behaviour when using more than one ternary operator within a single statement is non-obvious
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!