PHP gotcha of the day: echo AND print

Output suprises from using echo and print

Published on September 21, '11
by Serban Ghita
3
Comment
ShareThis

You will probably freak out because you have never saw echo and print working together, it's highly uncommon to see this in a production environment. Yet ... I've discovered an interesting PHP gotcha in the Zend Certified Engineer test question:

<?php
// What is the output of the following code?
echo '1' + print '2';
?>
Spoiler: Highlight to view
22
<?php
// What is the output of the following code?
echo print '4';
?>
Spoiler: Highlight to view
41
<?php
// What is the output of the following code?
echo print print 2;
?>
Spoiler: Highlight to view
211
<?php
// What is the output of the following code?
echo 1, print '2';
?>
Spoiler: Highlight to view
121

The explanation:

First of all keep in mind that echo and print are both language constructs and not functions. For any web developer this means that we don't have to use parentheses, but in the same time we have to keep in mind that everything that follows to echo, in the examples above are it's argument(s)! This is the key of interpreting this kind of code.

In the example:

<?php
echo '1' + print '2';
?>
  • '1' + print '2' is the argument
  • print '2' outputs 2 and returns 1
  • finally echo outputs '1' + 1, which is 2

Hence the final output 22.

This example is my favorite (imagine doing this in an interview):

<?php
echo 1, print '2';
?>

Comments

dicix
Written on: 22 September 2011
Get a life!!!
serban.ghita
Written on: 22 September 2011
<?php 
if($certification){
 return 
$life;
}
?>
dicix I know you liked it!
Allie
Written on: 22 September 2011
kudos for the blog!: )

Post new comment

This blog is intended to foster polite on-topic discussions. Comments failing these requirements and spam will not get published.