echo and printecho and print?Both echo and print are used to output data in PHP. They are almost identical, but echo is slightly faster because it does not return a value, whereas print returns 1.
Differences Between echo and print
| Feature | echo |
print |
|---|---|---|
| Return Value | No return value | Returns 1 (can be used in expressions) |
| Speed | Slightly faster | Slightly slower |
| Parameters | Can take multiple arguments | Takes only one argument |
Using echo
Single Value Output
<?php
echo "Hello, World!";
?>
✔ Outputs: Hello, World!
Multiple Arguments (Only with echo)
<?php
echo "Hello", " World", "!";
?>
✔ Outputs: Hello World!
With HTML Tags
<?php
echo "<h1>Welcome to PHP</h1>";
?>
✔ Displays: A heading Welcome to PHP
Using print
Single Value Output
<?php
print "Hello, World!";
?>
✔ Outputs: Hello, World!
Cannot Take Multiple Arguments
<?php
print "Hello", " World"; // ❌ This will cause an error
?>
Using echo and print in Variables
<?php
$name = "Alice";
echo "Hello, " . $name; // Using echo
print "Hello, " . $name; // Using print
?>
✔ Outputs:
Hello, Alice (twice, once from echo, once from print)
Conclusion
Use echo when you need better performance and multiple outputs.
Use print when you need to return a value (rare cases).