PHP echo and print

The echo and print statements are used for displaying output on web page like string, numbers, variables values etc. They are used in almost every PHP script.

PHP echo Statement

The echo statement is used to output data to the screen like string, numbers, variables values etc. The echo statement can be used to output HTML markup. We can use echo with or without parentheses: echo or echo().

Example

<?php
echo “Hello World!”;
echo “<h1>This is a heading</h1>”;
?>

PHP echo Display Variables

The following example shows how to output variables with the echo statement.

<?php
$num1 = 2;
$num2 = 4;

echo $num1;
echo “<br>The value of num2 is ” . $num2 . “<br>”;
echo $num1 + $num2;
?>

PHP print Statement

The print statement is an alternative to echo statement. It is used to output data on a web page. Like echo you can use print statement with or without parentheses like: print or print().

Example

<?php
print “Hello World!”;
print “<h1>This is a heading</h1>”;
?>

PHP print Display Variables

The following example shows how to output variables with the print statement.

<?php
$num1 = 2;
$num2 = 4;

print $num1;
print “<br>The value of num2 is ” . $num2 . “<br>”;
print $num1 + $num2;
?>

Difference Between echo and print

The echo and print statements are almost same with small differences.

  • echo has no return value while print has a return value of 1 so it can be used in expressions.
  • echo can take multiple parameters while print can take one argument.
  • echo is faster than print