Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "echo '2' . print(2) + 3" print 521? [closed]

Tags:

php

Can anybody tell the internal procedure of the below expression?

<?php echo '2' . print(2) + 3; ?>
// outputs 521
like image 348
naveen Avatar asked Nov 01 '12 11:11

naveen


4 Answers

print is not a function, so the parentheses don't work as you think. It's taking the value of the expression (2) + 3 (5) and outputs it. It returns 1 itself, which is concatenated to '2', which is then echoed.

like image 172
deceze Avatar answered Nov 16 '22 02:11

deceze


print(2) + 3 will result in 5 (it is the same as print (2 + 3) or print 2+3. Since print is not actually a function in this case, the parentheses are mostly meaningless. One last thing to note is that the print gets evaluated before the echo.

The output so far is: 5

echo '2' . print will result in 21 because print always returns 1

The output now is: '521'

like image 29
Joe Phillips Avatar answered Nov 16 '22 02:11

Joe Phillips


Echo a concatenated string composed of:

The string '2' The result of the function print('2'), which will return true, which gets stringified to 1 The string '3'

Now, the order of operations is really funny here, that can't end up with 521 at all! Let's try a variant to figure out what's going wrong.

echo '2'.print(2) + 3; This yields 521

PHP is parsing that, then, as:

echo '2' . (print('2') + '3')) Bingo! The print on the left get evaluated first, printing '5', which leaves us

echo '1' . print('2') Then the left print gets evaluated, so we've now printed '52', leaving us with

echo '1' . '1' ; Success. 521.

I would highly suggest not echoing the result of a print, nor printing the results of an echo. Doing so is highly nonsensical to begin with.

like image 25
user1535967 Avatar answered Nov 16 '22 02:11

user1535967


First the addition of 2 and 3 is done which results in 5 and that is output.

Next print returns 1 always. That return value is concatenated with 2 to get 21 which is then echoed.

like image 3
codaddict Avatar answered Nov 16 '22 04:11

codaddict