Printing Strings
There
are four ways to send output to the browser. The
echo construct lets you print many values at once,
while print( ) prints only one value. The
printf( ) function builds a formatted string by
inserting values into a template. The print_r( )
function is useful for debugging—it prints the contents of
arrays, objects, and other things, in a more-or-less human-readable
form.
echo
To put a string into the HTML of a
PHP-generated page, use echo. While it
looks—and for the most part behaves—like a function,
echo is a language construct. This means that you
can omit the parentheses, so the following are equivalent:
echo "Printy";
echo("Printy"); // also validYou can specify multiple items to print by separating them with commas:
echo "First", "second", "third";
FirstsecondthirdIt is a parse error to use parentheses when trying to echo multiple values:
// this is a parse error
echo("Hello", "world");Because echo is not a true function, you
can’t use it as part of a larger expression:
// parse error
if (echo("test")) {
echo("it worked!");
}Such errors are easily remedied, though, by using the print( ) or printf( ) functions.
print( )
The print( )
function sends one value
(its argument) to the browser. It returns true if
the string was successfully displayed and false
otherwise (e.g., if the user pressed the Stop button on her browser
before this part of the page was rendered):
if (! print("Hello, world")) {
die("you're not listening to me!");
}
Hello, worldprintf( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access