The echo statement can output one or more strings. In general, the echo statement can display anything that can be shown in the browser, such as strings, numbers, variable values, results of expressions, etc.
Since echo is a language construct, not a function (like the if
statement), you can use it without parentheses, for example, echo
or echo()
. However, if you want to pass more than one parameter to echo, the parameters must not be enclosed in parentheses.
The following example demonstrates how to display a string of text using the echo statement:
<?php
// Displaying string of text
echo "Hello World!";
?>
The output of the above PHP code will appear like this:
The following example demonstrates how to display HTML code using the echo statement:
<?php
// Displaying HTML code
echo "<h4>This is a simple heading.</h4>";
echo "<h4 style='color: red;'>This is heading with style.</h4>";
?>
The output of the above PHP code will appear like this:
The following example demonstrates how to display a variable using the echo statement:
<?php
// Defining variables
$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");
// Displaying variables
echo $txt;
echo "<br>";
echo $num;
echo "<br>";
echo $colors[0];
?>
The output of the above PHP code will appear like this:
You can also use the print statement (an alternative to echo
) to display output to the browser. Like echo, print is also a language construct, not a real function. Therefore, you can use it without parentheses, for example, print
or print()
.
Both echo
and print
statements work exactly the same way, except that the print
statement can only output one string and always returns 1. This is why the echo
statement is considered marginally faster than the print
statement since it doesn't return any value.
The following example demonstrates how to display a string of text using the print statement:
<?php
// Displaying string of text
print "Hello World!";
?>
The output of the above PHP code will appear like this:
The following example demonstrates how to display HTML code using the print statement:
<?php
// Displaying HTML code
print "<h4>This is a simple heading.</h4>";
print "<h4 style='color: red;'>This is heading with style.</h4>";
?>
The output of the above PHP code will appear like this:
The following example demonstrates how to display a variable using the print statement:
<?php
// Defining variables
$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");
// Displaying variables
print $txt;
print "<br>";
print $num;
print "<br>";
print $colors[0];
?>
The output of the above PHP code will appear like this: