In PHP, there are two primary ways to produce output: echo
and print
.
These two statements are frequently used in PHP scripts to display information.
Similarities and Differences
Both echo
and print
are used to output data to the screen. However, there are subtle differences between them:
echo
does not return a value, whileprint
returns 1, allowing it to be used in expressions.echo
can take multiple parameters, though this is rarely used, whereasprint
can only take one argument.echo
is slightly faster thanprint
.
The echo Statement
The echo
statement can be used with or without parentheses: echo
or echo()
.
Example:
echo "Hello";
//same as:
echo("Hello");
Displaying Text:
The following example demonstrates how to output text using the echo
command (notice that the text can contain HTML tags):
echo "<h2>Motorcycles are Cool!</h2>";
echo "Welcome to the motorcycle world!<br>";
echo "I'm excited to learn PHP!<br>";
echo "This ", "message ", "is ", "constructed ", "with multiple parameters.";
Displaying Variables:
The following example shows how to output text and variables with the echo
statement:
$brand1 = "Honda";
$brand2 = "Yamaha";
echo "<h2>$brand1</h2>";
echo "<p>Popular motorcycle brands include $brand2</p>";
Using Single Quotes
Strings can be surrounded by quotes, and there is a difference between using single and double quotes in PHP.
When using double quotes, variables can be embedded within the string directly. With single quotes, variables must be concatenated using the .
operator.
Example:
$brand1 = "Honda";
$brand2 = "Yamaha";
echo '<h2>' . $brand1 . '</h2>';
echo '<p>Popular motorcycle brands include ' . $brand2 . '</p>';
The print Statement
The print
statement can also be used with or without parentheses: print
or print()
.
Example:
print "Hello";
//same as:
print("Hello");
Displaying Text:
The following example demonstrates how to output text using the print
command (notice that the text can contain HTML tags):
print "<h2>Cars are Fun!</h2>";
print "Hello car enthusiasts!<br>";
print "I'm diving into PHP!";
Displaying Variables:
The following example shows how to output text and variables with the print
statement:
$model1 = "Tesla";
$model2 = "BMW";
print "<h2>$model1</h2>";
print "<p>Dream car brands include $model2</p>";
Using Single Quotes
When using double quotes, variables can be included directly within the string. However, with single quotes, variables must be concatenated using the .
operator.
Example:
$model1 = "Tesla";
$model2 = "BMW";
print '<h2>' . $model1 . '</h2>';
print '<p>Dream car brands include ' . $model2 . '</p>';