Home » Php » php – Why does "print" prints from right to left?

php – Why does "print" prints from right to left?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Can anyone please explain to me how this works:

<?php
    print 5 . print 6 . print 7;
?>

it prints: 76151

I know the 1 is the return value from the print function, but why are the functions called in reverse order?

How to&Answers:

I believe this occurs because the dot operator is left-associative.

The expression would look like this with parenthesis:

print 5 . (print 6 . (print 7));

Answer:

Your function is evaluating from right to left.

The trace is similar to this:

print (5 . print 6 . print 7)

print 7 evaluates first, printing 7 and returning 1.

print (5 . print 6 . 1)

This traces to print 61 and returning 1 Lastly:

print (5 . 1)

And thus you have 76151.

Answer:

Your expression can be written like this:

print (5 . print (6 . print 7));

print 61 and print 7 are return boolean 1, thats why 1 is also printed