Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine an echo and a print in one statement

Tags:

syntax

php

echo "1" . (print '2') + 3; returns 214. How does the script end up with *14?

like image 855
Michiel Avatar asked Feb 09 '12 15:02

Michiel


People also ask

What is echo and print statement?

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 .

What is the use of echo statement?

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.


1 Answers

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:

  • print 2, return 1
  • concat "1" with returned 1 => "11"
  • add "11" + 3 => 14
  • echo 14

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);
like image 147
Gordon Avatar answered Sep 22 '22 02:09

Gordon