In PHP, we use either echo
or print
to output strings. In this shot, we'll learn how and when to use these two PHP concepts.
echo
and print
The echo
and print
displays output data to the screen. But there are a few differences between them:
echo
accepts multiple parameters. print
only takes one, but concatenation is possible.
echo
does not have a return value, and print
always has a return value 1
.
echo
is faster than print because it has no return value.
print
can be used in a more complex expression because it has a return value.
echo has a shortcut syntax: <?=my string?>
.
Now, let’s look at some examples.
Note:
echo
andif
,for
...). There's no need to use parentheses () with them.
echo
<?phpecho "<h1>Educative, Inc</h1>";echo "<p>This is Educative. The best place to learn!</p>";echo '"echo"', " with multiple ", "parameters\n";$name = "Patience Kavira";echo "Your name is $name\n";// Non-string values are coerced to stringecho 5 * 5;
Notice how we use echo
in different scenarios.
Let's now see a situation where using echo
is not a good option:
<?php( 1 === 1 ) ? echo 'true' : 'false';
The code above is invalid.
As we said, echo
does not behave as an expression. So, it can't be used in this context. To fix this, we can either use print
or evaluate the expression first and pass it to echo
like this:
echo ( 1 === 1 ) ? 'true' : 'false';
print
<?phpprint "<h1>Educative, Inc</h1>";print "<p>This is Educative. The best place to learn!</p>";$name = "Patience Kavira";print "Your name is $name\n";// Non-string values are coerced to stringprint 5 * 5;// print in the context of expressionsif ( print " Abel" )echo " Sarah is out!\n";( 1 === 1 ) ? print 'true' : print 'false';
We also have situations where print
is not suitable. Try to run the code below:
<?phpprint '"print"', " with multiple ", "parameters?\n";
Running the code above outputs an error message.
This code outputs an error because we pass more than one parameter to print
. The solution here is to use either echo
or concatenation like this:
print '"print"' . ' with multiple' . ' parameters?\n';