PHP echo & print
In this page:
What is echo?
echo is the workhorse for sending output to the page — text, a variable's value, or a mix of both. It's a language construct rather than a real function, which is why it doesn't need parentheses and why you can hand it several comma-separated values in a single call.
Example: What is echo?
<?php
$name = "Alice";
echo "Hello, ", $name;
?>
Login to try C/C++/Java/PHP code in the editor
What is print?
print does the same basic job as echo — send text to the output — but it only accepts one argument, and it always evaluates to 1 as an expression. That return value is rarely used, but it does mean print can technically appear inside a larger expression in a way echo can't.
Example: What is print?
<?php
$result = print "Hello";
echo "\n" . $result;
?>
Login to try C/C++/Java/PHP code in the editor
echo with Multiple Arguments
echo's ability to take multiple comma-separated arguments (echo $first, ' ', $last;) is unique to it — print has no equivalent. Passing several values this way skips string concatenation entirely, which is a small but real performance win when you're building output from many pieces.
Example: echo with Multiple Arguments
<?php
$first = "John";
$last = "Doe";
echo $first, ' ', $last;
?>
Login to try C/C++/Java/PHP code in the editor
Outputting Variables
Double-quoted strings interpolate variables automatically, so echo "Hello, $name"; prints the variable's current value inline. Single-quoted strings skip interpolation and print $name as literal characters, which is faster but only useful when you genuinely don't need substitution.
Example: Outputting Variables
<?php
$name = "Alice";
echo "Hello, $name";
echo 'Hello, $name';
?>
Login to try C/C++/Java/PHP code in the editor
echo vs print
In practice echo is the default choice: it's marginally faster since it returns nothing, and it supports multiple arguments in one call. print's only edge is its return value, which is rarely what you actually need, so most PHP code you'll read favors echo almost exclusively.
Example: echo vs print
<?php
echo "echo", " ", "supports multiple args";
print "print only takes one";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: