PHP Tutorial Tutorials - PHP print

PHP print

Like PHP echo, PHP print is also a language construct not actually a real function.So you can also use it without parentheses like: print or print().

The major differences to echo are that print only accepts a single argument and always returns 1. So echo is faster than print.

PHP print: Display Strings of Text

<?php
print("Hello World");

print "print() also works without parentheses.";

print "This spans
multiple lines. The newlines will be
output as well";

print "This spans\nmultiple lines. The newlines will be\noutput as well.";

?>

Output:

Hello Worldprint() also works without parentheses.This spans
multiple lines. The newlines will be
output as wellThis spans
multiple lines. The newlines will be
output as well.

PHP print: Display Variables

<?php
// Defining variables
$str = "Hello World!";
$int = 798;
$arr = array(1,2,3);
 
// Displaying variables
print $str;
print "<br>";
print $int;
print "<br>";
foreach($arr as $value){
    print $value." ";
}
?>

Output:

Hello World!
798
1 2 3

Difference between echo and print

  • The major differences to echo are that print only accepts a single argument .
  • echo doesn't return any value,print always returns 1
  • echo is faster then print
<?php
// multiple arguments
echo 'multiple ', 'parameters';

// Invalid print only accepts a single argument
print 'multiple ', 'parameters';
// Parse error: syntax error, unexpected ','

$var = print 'Hello'.PHP_EOL;
var_dump($var);
// int(1)
?>

Why is faster? echo VS print

We can dump the opcodes:
print.php

<?php
echo 'lautturi';
?>
$ php -d vld.active=1 print.php

number of ops:  4
compiled vars:  none
line     #  op                     fetch  ext  return  operands
--------------------------------------------------------------
   1     0  PRINT                              ~0      'lautturi'
         1  FREE                                       ~0
   2     2  RETURN                              1
         3* ZEND_HANDLE_EXCEPTION

echo.php

<?php
echo 'lautturi';
?>
$ php -d vld.active=1 echo.php

number of ops:  3
compiled vars:  none
line     #  op                     fetch   ext  return  operands
------------------------------------------------------------------
   1     0  ECHO                                        'lautturi'
   2     1  RETURN                                 1
         2* ZEND_HANDLE_EXCEPTION  

print uses one more opcode. But one opcode costs nothing.
And php need to checks if echo has multiple values(arguments) to display or not.
print only accepts a single argument.So the difference is very subtle.

you can use both of them even if a script have hundreds of calls to them.

Date:2019-10-01 01:07:44 From:www.Lautturi.com author:Lautturi