To display data or HTML in a browser using PHP, you primarily use two statements: echo and print. While they perform almost identical tasks, there are small differences in how they function under the hood.
echo is the most commonly used output statement in PHP. It is slightly
faster than print and can take multiple parameters (though this is rarely
used).
<?php
echo "Hello World!";
echo "<h3>PHP is Fun!</h3>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
You can use echo with or without parentheses: echo or
echo().
print works very similarly to echo. The key difference is that
print always returns a value of 1, meaning it can be used
in expressions.
<?php
print "Hello World!";
print "<p>I am learning PHP!</p>";
?>
Both echo and print are used to output variable values on the
screen. Note how we use the dot operator (.) for string
concatenation.
<?php
$txt1 = "Learn PHP";
$txt2 = "RedoHub";
$x = 5;
$y = 4;
echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>
" "),
PHP will process variables automatically. Inside single quotes (' '), it
will display the variable name literally.
<?php
$name = "Alice";
echo "Hello $name"; // Outputs: Hello Alice
echo 'Hello $name'; // Outputs: Hello $name
?>
| Feature | echo | |
|---|---|---|
| Speed | Slightly faster | Slightly slower |
| Return Value | No return value | Returns 1 (can be used in expressions) |
| Parameters | Can take multiple strings | Takes only one argument |
echo by default unless there
is a specific need for a return value. It is the industry standard for sending HTML to
the browser.
.) to join strings and variables.