PHP 5 echo and print Statements
In PHP, there are two basic ways to get output: echo and print.
In this section, we will discuss in detail the usage of both statements and demonstrate how to use echo and print with examples.
PHP echo and print Statements
Differences between echo and print:
- echo - Can output one or more strings
- print - Allows output of only one string, always returns 1
Tip: echo is faster than print, echo has no return value, print returns 1.
PHP echo Statement
echo is a language construct, which means it can be used without parentheses, or with parentheses: echo or echo().
Displaying Strings
The following example demonstrates how to use the echo command to output strings (strings can include HTML tags):
Example
<?php
echo "<h2>PHP is interesting!</h2>";
echo "Hello world!<br>";
echo "I want to learn PHP!<br>";
echo "This is a", " string,", " using", " multiple", " parameters.";
?>
Displaying Variables
The following example demonstrates how to use the echo command to output variables and strings:
Example
<?php
$txt1 = "Learn PHP";
$txt2 = "tutorialpro.org";
$cars = array("Volvo", "BMW", "Toyota");
echo $txt1;
echo "<br>";
echo "Learn PHP at $txt2";
echo "<br>";
echo "My car brand is {$cars[0]}";
?>
PHP print Statement
print is also a language construct, which means it can be used with or without parentheses: print or print().
Displaying Strings
The following example demonstrates how to use the print command to output strings (strings can include HTML tags):
Example
<?php
print "<h2>PHP is interesting!</h2>";
print "Hello world!<br>";
print "I want to learn PHP!";
?>
Displaying Variables
The following example demonstrates how to use the print command to output variables and strings:
Example
<?php
$txt1 = "Learn PHP";
$txt2 = "tutorialpro.org";
$cars = array("Volvo", "BMW", "Toyota");
print $txt1;
print "<br>";
print "Learn PHP at $txt2";
print "<br>";
print "My car brand is {$cars[0]}";
?>