Wednesday, June 26, 2019

echo vs print Statement in PHP

There are two basic ways to get output in PHP:
  • echo
  • print

PHP echo statement

In PHP echo statement is a language construct and not a function, so it can be used without parentheses. But we are allowed to use parentheses with echo statement when we are using more than one arguments with it. The end of the echo statement is identified by the semi-colon (';').
We can use echo to output strings or variables. Below are some of the usage of echo statement in PHP:

Displaying Strings: We can simply use the keyword echo followed by the string to be displayed within quotes. Below example shows how to display strings with PHP:

<?php
echo "Hello, This is echo vs print statement!";
?>

Output: Hello, This is echo vs print statement!

Displaying Strings as multiple arguments: We can pass multiple string arguments to the echo statement instead of a single string argument, separating them by comma (,) operator.

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

Output: Hello! PHP World

PHP print statement

The PHP print statement is similar to the echo statement and can be used alternative to echo at many times. It is also language construct and so we may not use parentheses: print or print().
Like echo, print statement can also be used to print strings and variables. Below are some examples of using print statement in PHP:

Displaying String of Text: We can display strings with print statement in the same way  as we did with echo statements. The only difference is, we cannot display multiple strings separated by comma(,) with a single print statement.

<?php
print "Hello World!";
?>
Output: Hello World!


Difference Between echo and print Statement

  • echo can accept multiple arguments while print only accepts a single argument
  • echo doesn't have a return value while print always returns 1
  • echo is marginally faster than print


0 comments:

Post a Comment