phpoutputlanguage-construct

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


Can anybody tell the internal procedure of the below expression?

<?php echo '2' . print(2) + 3; ?>
// outputs 521

Solution

  • 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.