This article mainly introduces a problem and solution encountered about PHP conditional operators. It has a certain reference value. Now I share it with you. Friends in need can refer to it.
Encountered today Come to a question about the nested use of conditional operators (ternary expressions) in PHP
Let’s first look at a piece of C language code (test.c):
#include<stdio.h> int main() { int x = 1; int shit = x == 1 ? 100 : x == 2 ? 200 : 300; printf("shit的值:%d\n", shit); return 0; }</stdio.h>
Compile and run it
root$ gcc test.c -o test && ./test shit的值:100
The answer is as expected, because x==1, so 100 is assigned to shit.
But if we rewrite the above code in PHP (test.php):
<?php $x = 1; $shit = $x == 1 ? 100 : $x == 2 ? 200 : 300; echo "shit的值:$shit\n";
Execute it:
root$ php test.php shit的值:200
We find that it returns The results are different, why is this?
First of all, we suspect that it may be a priority issue with comparison operator(==) and conditional operator(?:) in PHP , let’s check the PHP official documentation
##== has a higher priority than ?: (C language This is also true), so
$shit = $x == 1 ? 100 : $x == 2 ? 200 : 300;
$shit = ($x == 1) ? 100 : ($x == 2) ? 200 : 300;
operator combination direction:
This is very similar to the phenomenon described above, The problem should be here. After some research, I got the following conclusion:
Conclusionfrom right to left, each evaluation starts from the rightmost subexpression, so
int x = 1; int shit = x == 1 ? 100 : x == 2 ? 200 : 300; //等效于 int shit = x == 1 ? 100 : (x == 2 ? 200 : 300); //等效于 int shit = x == 1 ? 100 : (300);// 100
from left to right, and each evaluation starts from the leftmost subexpression, so
$x = 1; $shit = $x == 1 ? 100 : $x == 2 ? 200 : 300; //等效于 $shit = ($x == 1 ? 100 : $x == 2) ? 200 : 300; //等效于 $shit = (100) ? 200 : 300;// 200
is between PHP Conditional operator combination direction, we cannot achieve the effect of if-elseif-elseif-else expression by nesting conditional operators like C/C, unless we add parentheses to the later sub-expressions , in this example it can be solved in this way:
$shit = $x == 1 ? 100 : ($x == 2 ? 200 : 300);
$shit = $x == 1 ? 100 : ($x == 2 ? 200 : ($x== 3 ? 300 : ... ($x == 8 ? 800 : 900)))))));
It is recommended that you avoid "stacking" ternary expressions. PHP'sThe above is The entire content of this article is hoped to be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website! Related recommendations:
behaviour when using more than one ternary operator within a single statement is non-obvious
Let’s talk about dependency injection, containers and appearance patterns in framework development (Part 2)
How to solve the problems of PHP Problems with concurrency and large traffic
The above is the detailed content of About a problem encountered by PHP conditional operator and its solution. For more information, please follow other related articles on the PHP Chinese website!