echo "1" . (print '2') + 3;
returns 214. How does the script end up with *14?
They are both used to output data to the screen. The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print .
echo is a statement, which is used to display the output. echo can be used with or without parentheses: echo(), and echo. echo does not return any value. We can pass multiple strings separated by a comma (,) in echo.
When you do
echo "1" . (print '2') + 3;
PHP will do (demo)
line # * op fetch ext return operands
---------------------------------------------------------------------------------
2 0 > PRINT ~0 '2'
1 CONCAT ~1 '1', ~0
2 ADD ~2 ~1, 3
3 ECHO ~2
4 > RETURN 1
In words:
and that's 214.
The operators + - .
have equal Operator Precedence, but are left associative:
For operators of equal precedence, left associativity means that evaluation proceeds from left to right, and right associativity means the opposite.
Edit: since all the other answers claim PHP does 1+3, here is further proof that it doesnt:
echo "1" . (print '2') + 9;
gives 220, e.g. 11+9 and not 1 . (1+9)
. If the addition had precedence over the concatenation, it would have been 2110, but for that you'd had to write
echo "1" . ((print '2') + 9);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With