Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP unexpected order with print and echo

When i execute the code: echo 'a' . print('2') . 'c'; i get 2ca1.

I can figure out that print('2') write down 2 and echo print('1') will print 1

But why letter ‘c’ is wrtitten down after print statement and not at the end?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was expecting to see ‘2a1c’ instead.

>Solution :

print is not really a function, but a language construct.

As the manual points out,

Surrounding the argument to print with parentheses will not raise a syntax error, and produces syntax which looks like a normal function call. However, this can be misleading, because the parentheses are actually part of the expression being output, not part of the print syntax itself.

If ('2') is only an expression here, then it means this is basically the same, as print '2' . 'c' – so that concatenation happens first, and then the result of it gets printed.

And then the return value of print – always 1 – gets concatenated to the a, and then the echo causes the latter, a1, to be written to the output buffer, after the already print-ed 2c.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading