Why echo and print are not Functions in PHP and their differences

Updated on September 3, 2017

I hear few of my colleagues call ‘echo‘ and ‘print‘ as functions in PHP. But actually they are not. According to the descriptions from ‘php.net‘, echo and print are language constructs and not functions. It means, you are not required to use parenthesis for both ‘echo‘ and ‘print‘ (you can use parenthesis, but not necessarily), as they don’t behave like functions. Whereas in function, parenthesis is must.

Learn: Difference between die and exit functions in PHP

Difference between echo and print

Basically echo and print does the same job – outputs data to the screen, but there are few marginal differences between them.

echo and print php

Echo:

  • As told, echo is used to output data to the screen and it’s a language construct. echo can be used with or without parentheses.
  • echo can take more than one argument separated by commas.
  • echo doesn’t have a return value
  • echo is slightly faster than ‘print’

1. echo with or without parentheses

<?php
 echo "Hello..." . "<br />";
 echo ("Hello.." . "<br />");
 $txt = "Sample text";
 echo $txt . "<br />";
 echo ($txt . "<br />");
?>

Output:

Hello...
Hello..
Sample text
Sample text

2. echo can take multiple arguments

<?php
 echo "Hello ", "PHP ", "is ", "awesome", "<br />";
 $txt = "is fun as well";
 echo "And PHP ", $txt;
?>

Output:

Hello PHP is awesome
And PHP is fun as well

And since it’s not a function, you can’t pass multiple arguments within parentheses. The parser will throw “syntax error, unexpected”.

<?php
 echo ("no multiple args","inside parentheses"); //Parse error: syntax error, unexpected ','
?>

3. ‘echo’ does not return value. The parser will output an error “syntax error, unexpected ‘echo’ (T_ECHO)”

<?php
 $txt = "Sometext";
 $return_value = echo $txt; //syntax error, unexpected 'echo' (T_ECHO)
?>

Print:

  • As told, print is a language construct and can work with or without parenthesis.
  • print cannot take more than one argument.
  • print has a return value
  • print is slightly slower than echo

1. ‘print’ with or without parentheses

<?php
 print "Hello..." . "<br />";
 print ("Hello.." . "<br />");
 $txt = "Sample text";
 print $txt . "<br />";
 print ($txt . "<br />");
?>

Output:

Hello...
Hello..
Sample text
Sample text

2. ‘print’ cannot take multiple arguments

<?php
 print "Hello ", "PHP ", "is ", "awesome", "<br />";
 $txt = "is fun as well";
 print ("And PHP ", $txt);
?>

Output:

syntax error, unexpected ','

3. ‘print’ has a return value

<?php
 $txt = "Sometext";
 $return_value = print $txt . "<br />";
 print "The return value is " . $return_value;
?>

Output:

Sometext
The return value is 1

Was this article helpful?

Related Articles

Leave a Comment