The following code outputs 43211
, why?
echo print('3').'2'.print('4');
The following code outputs 43211
, why?
echo print('3').'2'.print('4');
print
is returning 1
On the documentation
Return Values: Returns 1, always.
You should just probably stick to using echo
.
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.
Your statement parses to humans as follows.
Echo a concatenated string composed of:
print('3')
, which will return true, which gets stringified to 1
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 echo
ing the result of a print
, nor print
ing 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.