What is the difference between PHP print and echo statements?

In every programming language available today, there is usually more than one way to display output to the screen. PHP has two methods:

  • echo statements.
  • print statements.

echo statements

This is the most commonly used of the two functions used to display output in PHP. echo can be used with or without parentheses and can take several strings and variables concatenated together.

Code

<?php
$toDisplay = 200;
$$toDisplayMyName = ',You will see me on screen';
$insideHtml = ",An Html paragragh,";
//can display content of a variable be it a string or not
echo $toDisplay;
echo $$toDisplayMyName;
//used to dispay a string which must be qouted "" or '';
echo ",Now is double qoute";
echo ',Now is double qoute';
// can display concatenated strings and variables;
echo ",You can display string & variables".$toDisplay;
//can also be used to echo html codes/components
/* echo '<P>'$insideHtml'</p>'
This won't exucute properly here becuase this
playground only understand php code.
*/;
//using it with parentheses
echo (",used with parentheses");
// Can take multiple comma separated parameters
echo $insideHtml,$$toDisplayMyName,$toDisplay;
?>

The code above includes scenarios of how we can use the echo statement.

print statements

The print statement in PHP is what you might call a pseudo function. This is because it returns a value 1 like a function, but it is not callable like functions are.

Although the print statement can be used in almost the same way as the echo statement in the code above, it cannot print multiple parameters. The print statement’s main importance is that it can be used inside expressions and even in conditions, unlike the construct echo, which must be used at the start of a new line.

Code

<?php
$m = 4;
$n = 5;
//you can say do
echo print $n + $m;
/*where 1 in the output of above code is
the return value of print.*/
//but not
print echo $n + $m;
/*Above will throw an error
*comment it out to see the output of others*/
?>

You can also use the print statement to do print out to the screen inside your conditions, as shown below.

<?php
/*This code will increment the counter with
the return value of the print statement while
printing the curent value of the counter.*/
/*the echo will
display the final value of the counter*/
for ( $i = 0; $i < 10; $i += print "$i," );{
echo $i;
}
?>

Try exchanging echo for print and vice versa in the code above and see what happens.

Differences between echo and print statements


Echo

Print

1

Can output multiple parameters

Only outputs concatenated strings or parameters

2

Has no return value

Has a return value of 1

3

Returns nothing, and is slightly faster

Has a return value, and slows down slightly

4

Can't be used within expressions

Can be used within expressions and conditions

Free Resources