Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use print instead of echo in PHP?

Tags:

php

echo

printing

I understand that echo is slightly faster, and print can be used as a function, but I've been reading an e-book on PHP, and the writer is using print, instead of echo, to output very simple text.

print "Your name is $name\n";

So my question is, when would it be appropriate for me to use print as opposed to echo?

like image 423
Rob Avatar asked Apr 23 '10 06:04

Rob


People also ask

Why is preferable over with echo print in PHP?

Echo vs Print Echo can be used in expressions as it has no return value while print has a return value of 1. echo is marginally faster than print and can take multiple parameters while print can take only one argument.

What can I use instead of echo in PHP?

You can also use the print statement (an alternative to echo ) to display output to the browser. Like echo the print is also a language construct not a real function. So you can also use it without parentheses like: print or print() .

What is the use of print in PHP?

PHP: print() function The print() function used to output one or more strings. The print() is not a real function, it is a language construct. Therefore there is no need to use parentheses with its argument list. The input string.


2 Answers

Never.

Definitely a micro optimisation.

Some may find it useful as the and print trick. But ugly as hell and not recommended.

like image 164
alex Avatar answered Nov 10 '22 09:11

alex


IMHO the main difference is that you can print multiple values with echo without concatenating them, i.e., echo $a, $b, $c;. As far as I know, it's not possible to do this with print. If you want to use this syntax (and I would advise to use it whenever possible, although I'm not 100% sure that it is faster in real-world apps), it would be better to always use echo, as mixing both ways would lead to inconsistency.

like image 41
binaryLV Avatar answered Nov 10 '22 07:11

binaryLV