PHP Echo / Print
echo and print both send text to the browser (or stdout). They differ in a couple of small ways.
echo
PHP
<?php echo 'Hello'; echo 'Hello', ' ', 'world', PHP_EOL; // multiple args separated by commas echo "Hello, $name", PHP_EOL; // interpolation in double quotes
- Accepts multiple comma-separated arguments.
- Not technically a function — no return value, no parens required.
- Slightly faster than
printin microbenchmarks (rarely matters).
PHP
print 'Hello';
print('Hello, ' . $name);
$rc = print 'side effect'; // returns 1 — usable in expressions
- Takes exactly one argument.
- Returns 1 — usable inside expressions.
Short echo tag
In templates, <?= ?> is shorthand for <?php echo ?>:
PHP
<p>Hello, <?= htmlspecialchars($name) ?>!</p>
Newlines
| Constant / char | Output |
|---|---|
PHP_EOL | OS-appropriate line ending. |
"\n" | Literal LF (in double-quoted strings). |
'\n' | Two literal characters — useless. |
'<br>' | HTML line break — for browser output. |
Tip: Always wrap user-supplied data in
htmlspecialchars() before echoing it into HTML. Otherwise you've shipped an XSS bug.Example
Example
<?php echo 'one', ' ', 'two', PHP_EOL; // multiple args, no return print 'three' . PHP_EOL; // single arg, returns 1Try it Yourself »
Exercise
Short echo tag for templates is…
<
= htmlspecialchars($name) ?>
One character.
Discussion
Loading…