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 valid
You can specify multiple items to print by separating them with commas:
echo"First","second","third";Firstsecondthird
It is a parse error to use parentheses when trying to echo multiple values:
// this is a parse errorecho("Hello","world");
Because echo is not a true
function, you can’t use it as part of a larger expression:
// parse errorif(echo("test")){echo("It worked!");}
Such errors are easily remedied, by using the print() or printf() functions.
print()
The print() construct
sends one value (its argument) to the browser:
if(("test\n")){("It worked!");}testItworked!
printf()
The printf() function
outputs a string built by substituting values into a template (the
format string). It is derived from the function of
the same name in the standard C library. The first argument to printf() is the format ...
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