- URL: https://www.laruence.com/en/2019/03/01/4904.html
- Please include attribution when republishing.
This comes from a seemingly bizarre problem:
if (print("1\n") && print("2\n") && print("3\n") && print("4\n")) {
;
}
What do you expect this code to output?
The actual output is:
4 111
Often we overlook the fact that print is a language construct, not a function. Its argument list doesn't require parentheses (even if you write them, the parentheses are ignored during parsing). It's simply an "expression" that always returns 1:
expr :
T_PRINT expr
| '(' expr ')'
;
So in PHP's view, the code above is really:
if (print ("1\n" && print ("2\n" && print ("3\n" && print "4\n")))) {
;
}
That is, it outputs 4, then outputs "3\n" && the result of print which is 1, then outputs "2\n" && 1, and finally "1\n" && 1.
If we actually want to achieve the original intent of the code above, we should write it like this:
if ((print "1\n") && (print "2\n") && (print "3\n") && (print "4\n")) {
;
}
Be First to Comment