Differences between echo and print in PHP

  • 2021-07-16 02:04:34
  • OfStack

Generally speaking, the dynamic output of HTML content in PHP is realized by print and echo statements. In actual use, the functions of print and echo are almost identical. It can be said that wherever one can be used, the other can also be used. However, there is also a very important difference between the two: in the echo function, multiple strings can be output at the same time, while in the print function, only one string can be output at the same time. Also, the echo function does not require parentheses, so the echo function is more like a statement than a function.
echo and print are not functions, but language constructs, so parentheses are not required.

The difference between them is:

(1) echo can output multiple strings like this:


echo 'a','b','c';

If you have to put parentheses, pay attention to writing echo ('a', 'b', 'c'); Is wrong, it should be written as:


echo ('a'),('b'),('c');

It does not behave like a function, so it cannot be used in the context of a function
(2) print can only output 1 string. It can behave like a function. For example, you can use the following:


$ret = print 'Hello World';

So it can be used in more complex expressions.
In addition, the efficiency of echo is relatively fast!

Look at the following code:


<?php
$a='hello ';$b='php world!';echo $a,$b.'<br />';//echo  You can separate string variables with commas to display 
print $a.$b.'<br />';// And print You can't use commas, you can only use dots to separate them. 
//print $a,$b.'<br />';// Commas are used here to report errors. 
?>

Analysis and summary:

The echo command is the same as the print command, and there is no difference
The echo function is different from the print function.
echo () has no return value, the same as the echo command
print () has a return value, success, return 1, false, return 0.
printf () is similar to sprintf () in that both output is formatted, except that the former outputs to standard output and the latter to variables

In the form of:


echo  <<< EOT 
EOT; 
print  <<< EOT 
EOT; 

The writing format of, its meaning is as follows:

< < < Operator, which treats the contents between custom delimiters as strings and can handle variables between them
EOT custom delimiter, which must end at the beginning of the line

Believe that this article for everyone to better grasp the PHP programming has a certain reference value.


Related articles: