tags:

views:

104

answers:

3

The following code outputs 43211, why?

  echo print('3').'2'.print('4');
+2  A: 

print is returning 1

On the documentation

Return Values: Returns 1, always.

You should just probably stick to using echo.

alex
I still don't understand why does it output in that order (43211)?
Tunji Gbadamosi
@Tunji Gbadamosi Please see [Charles' answer](http://stackoverflow.com/questions/3340330/strange-echo-print-behaviour-in-php/3340367#3340367).
alex
A: 

You are using a function within a function as alex said. Just simply use echo or print.

echo '3'.'2'.'4'; 

will return properly or likewise for print.

RageD
`print` technically is a language construct.
alex
Yes, it's generally only more useful if you are looking for a return value upon the completion. But for something as simple as this it would work nearly the same; minus the retval of course that print would give and echo would not. In extreme cases, echo is probably faster.
RageD
+7  A: 

Your statement parses to humans as follows.

Echo a concatenated string composed of:

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

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

echo '1' . print('2') . '3' . print('4') . '5';

This yields 4523111

PHP is parsing that, then, as:

echo '1' . (print('2' . '3')) . (print('4' . '5'));

Bingo! The print on the left get evaluated first, printing '45', which leaves us

echo '1' . (print('2' . '3')) . '1';

Then the left print gets evaluated, so we've now printed '4523', leaving us with

echo '1' . '1' . '1';

Success. 4523111.

Let's break down your statement of weirdness.

echo print('3') . '2' . print('4');

This will print the '4' first, leaving us with

echo print('3' . '2' . '1');

Then the next print statement is evaluated, which means we've now printed '4321', leaving us with

echo '1';

Thus, 43211.

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.


Upon further review, I'm actually not entirely sure how PHP is parsing either of these bits of nonsense. I'm not going to think about it any further, it hurts my brain.

Charles
+1 great answer Charles
alex
+1 I'd add that the language construct `print` doesn't get evaluated the same way functions do, hence the weird order. I'd almost go as far as saying that this nesting produces more or less undefined behavior.
deceze
Well, I'd like to thank you for this VERY illuminating answer.
Tunji Gbadamosi
Almost right - print is a language construct. The parentheses are ignored by the language. print(3) . '2'; is the same thing as print 3 . '2';
mercutio