PHP Echo vs Print
PHP: Difference between echo and print
Going over some PHP code I noticed that echo
and print
were being used [almost] interchangeably.
Print Takes Only One Parameter
Another difference is that while echo
can take multiple parameters, print
only takes one.
echo "Output is one, ", "two", "three";
print("Single argument");
echo
Does Not Behave Like A Function
Whilst both echo
and print
are language constructs, echo
does not behave like a function.
You don't need to use parentheses with either of them, and, most of the time you can use them interchangeably.
$condition = TRUE;
($condition) ? print "true" : print "false";
true
$condition = TRUE;
($condition) ? echo "true" : echo "false";
//PHP Parse error: syntax error, unexpected 'echo' (T_ECHO)
To make it work with echo
we just have to update the statement to:
$condition = TRUE;
echo $condition ? "true" : "true";
//PHP Parse error: syntax error, unexpected 'echo' (T_ECHO)
This might seem a little bit contrived, but it's only an example. A situation where I like to take advantage of the fact that print
behaves as a function:
//Usually quick debug fix
myMethod() AND print('myMethod: OK') OR print('myMethod: KO'.generateError());
echo
Is Faster
Since print
does return something is a little bit slower than echo
but not worth taking into account. Really.