PHP Echo / Print
PHP Echo and Print: Writing Output from PHP Scripts
echo and print are the two core language constructs for sending text, numbers, and HTML to the browser or terminal in PHP. Both work without parentheses, though echo is used almost everywhere because it accepts multiple arguments and returns nothing.
Comparing echo and print
While both constructs output strings, their signatures differ slightly under the hood.
| Feature | echo |
print |
|---|---|---|
| Return Value | None (void) |
Always returns 1 |
| Multiple Arguments | Supported (echo $a, $b;) |
Single argument only |
| Expression Use | Cannot be used inside expressions | Can be used inside expressions |
| Template Shortcut | <?= $value ?> |
No dedicated shortcut |
Because echo has no return value overhead and supports comma-separated values, developers favor it for CLI scripts and template output. Using commas instead of string concatenation with . also avoids allocating an intermediate joined string in memory.
<?php
declare(strict_types=1);
$productName = "Mechanical Keyboard";
$price = 89.00;
$inStock = true;
echo "Product: ", $productName, " | Price: $", number_format($price, 2), PHP_EOL;
print "Status: " . ($inStock ? "Available" : "Sold Out") . PHP_EOL;
Safe HTML Output with <?= ?>
When generating HTML responses, wrap any user-supplied text with htmlspecialchars() before echoing it. This converts < and > characters into safe HTML entities.
<?php
$username = "<script>alert('xss')</script>Samir";
$safeName = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
?>
<div class="user-badge">
<p>Signed in as: <strong><?= $safeName ?></strong></p>
</div>
Common Mistakes to Avoid
- Passing multiple arguments to
print: Writingprint $a, $b;throws aParseError. Onlyechoaccepts comma-separated arguments. - Echoing arrays directly: Running
echo [1, 2, 3];triggers an "Array to string conversion" warning. Useprint_r(),var_dump(), orimplode(). - Forgetting
ENT_QUOTESwithhtmlspecialchars(): Always includeENT_QUOTESand'UTF-8'when escaping values placed inside HTML attributes.
Frequently Asked Questions
Is echo a function in PHP?
No. Both echo and print are language constructs, not functions, which means parentheses around the argument are optional.
Which is faster in PHP 8: echo or print?
echo is marginally faster because it does not return an integer 1, though in real web apps the difference is negligible.
How do I print arrays or objects for debugging?
Use var_dump($data) to inspect types and values, or json_encode($data, JSON_PRETTY_PRINT) for clean readable output.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.