Difference between echo and print in PHP

This article is created to differentiate the two famous keywords or statements, which are:

To output data to the client or the browser in PHP, you can use the echo and print statements. Since they are both linguistic constructions and not functions, they can both be used without parentheses.

PHP echo vs. print

echo print
Takes more than one argument Takes only one argument
Does not return any value Always returns 1
Can not be used as an expression Can be used as an expression
Little faster than print Little slower than echo

PHP echo vs. print example

Consider the following PHP code as an example of "echo vs. print."

<?php
   print "fresherearth";
   echo "<hr>";
   echo "codes", "cracker";
   echo "<hr>";
   $x = 120;
   $x ? print "'x' is defined" : print "'x' is not defined";
?>

The output of the above PHP example is:

difference between echo and print php

The above PHP code consists of three statements that demonstrate the use of print and echo statements, along with a ternary operator for conditional output. Here's what each statement does:

print "fresherearth";

This statement uses the print statement to output the string "fresherearth" to the browser. The print statement is equivalent to the echo statement and can be used interchangeably.

echo "<hr>";

This statement uses the echo statement to output an HTML horizontal rule to the browser. The <hr> tag creates a horizontal line on the webpage.

echo "codes", "cracker";

This statement demonstrates that echo can take multiple parameters separated by commas, just like print. Here, it outputs the string "fresherearth" to the browser, but with a subtle difference: the echo statement does not add any space or separator between the two strings, whereas print would add a space by default.

$x = 120; $x ? print "'x' is defined" : print "'x' is not defined";

This statement demonstrates the use of the ternary operator, a shorthand for an if-else statement. Here, it assigns the value 120 to the variable $x, and then checks whether $x evaluates to true or false. If $x is true, it prints the string "'x' is defined"; otherwise, it prints the string "'x' is not defined". Since 120 is a non-zero value and evaluates to true, the output of this statement will be: 'x' is defined.

Let me include one last example before closing the discussion on "echo vs. print."

PHP Code
<?php 
   echo "Hello ", "World", "!<br>";
   print "Hello World!<br>";

   $string = "Hello World";
   $result = print($string);
   echo "<br>Result of print statement: $result<br>";
?>
Output
Hello World!
Hello World!
Hello World
Result of print statement: 1

PHP Online Test


« Previous Tutorial Next Tutorial »