What are echo and print in PHP?
Overview
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.
Understanding echo and print
The echo and print displays output data to the screen. But there are a few differences between them:
echoaccepts multiple parameters.printonly takes one, but concatenation is possible.echodoes not have a return value, andprintalways has a return value1.echois faster than print because it has no return value.printcan 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:
echoandif,for...). There's no need to use parentheses () with them.
Examples with 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';
Examples with 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';