9

Possible Duplicates:
How are echo and print different in PHP?
Is there any difference between ‘print’ and ‘echo’ in PHP?
What’s the difference of echo,print,print_r in PHP?

There are several ways to print output in PHP; including but not limited to:

echo 'Hello';
echo ('Hello');
print 'Hello';
print ('Hello');

Are there any differences between these four? Also, do the parentheses make any difference at all?

Community
  • 1
  • 1
Aillyn
  • 23,354
  • 24
  • 59
  • 84

1 Answers1

2

Two differences:

print has a return value (always 1), echo doesn't. Therefore print can be used as an expression.

echo accepts multiple arguments. So you may write echo $a, $b instead of echo $a . $b.

Concerning the parentheses: They are simply wrong in my eyes. They have no function at all. You could as well write echo (((((((((($a)))))))))); people usually include parentheses from ignorance, thinking that print is a function. Furthermore it increases the chance of misinterpretation. For example print("foo") && print("bar") does not print foobar, because PHP interprets this as print(("foo") && print("bar")). So bar1 would be printed, even though it looks different.

NikiC
  • 100,734
  • 37
  • 191
  • 225
  • I know Python is not PHP, but they [banned](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function) the use of `print 'something'`, now you always have to use `print('something')` with the parentheses. – Aillyn Aug 22 '10 at 18:44
  • Also see: http://www.ideone.com/LUOOG – Aillyn Aug 22 '10 at 18:57
  • No. It does make a difference. Even though it outputs the same the version with parentheses *looks* different. The parentheses and function like formatting make it look different. At least I would be fooled into thinking that it outputs `foobar`, if I didn't stop to think about it. – NikiC Aug 22 '10 at 19:00
  • 1
    Yes, you are right, it outputs the same thing. Maybe I didn't explain my point clearly. I'm talking about the understandability of the code, not of the functionality. The functionality doesn't change, that's correct. – NikiC Aug 22 '10 at 19:03
  • Though there actually is one case, there using parentheses will not only make the code less understandable, but will actually break things. If you have a function which returns by reference `return($a)` will not work, because it will not return a reference to `$a`, but the result of the expression `($a)`, which obviously is a value, not a reference. But this is off topic, because we're talking about print and echo ^^ – NikiC Aug 22 '10 at 19:09
  • @nik Do elaborate. I can't see how it would be different – Aillyn Aug 22 '10 at 19:19
  • @nik the part about references – Aillyn Aug 22 '10 at 19:27
  • Simply see the third note on http://php.net/return. It is explained there. – NikiC Aug 22 '10 at 19:29