Home » Php » printing – When should I use print instead of echo in PHP?

printing – When should I use print instead of echo in PHP?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

Never.

Definitely a micro optimisation.

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

Answer:

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.

Answer:

print and echo are commands used to output information to the visitors screen (on the web page). Both do the same job, so it usually comes down to a matter of personal preference on which one you like to use.

There is a slight difference between print and echo which would depend on how you want to use the outcome. Using the print method can return a true/false value. This may be helpful during a script execution of somesort. Echo does not return a value, but has been considered as a faster executed command. All this can get into a rather complicated discussion, so for now, you can just use whichever one you prefer.

Answer:

It really doesn’t matter. This kind of optimization is most of the time micro optimization, which most of the time is fruitless.