iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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 print in microbenchmarks (rarely matters).

print

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 / charOutput
PHP_EOLOS-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 1
Try it Yourself »

Exercise

Short echo tag for templates is…

< = htmlspecialchars($name) ?>

Test yourself

Q1. echo accepts…
Q2. print returns…
Q3. A safe way to embed user input in HTML is…

Discussion

Loading…