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 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, 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, world
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 string. The
remaining arguments are the values to be substituted. A % character in
the format string indicates a substitution.
Format modifiers
Each substitution marker in the template consists of a
percent sign (%
), possibly
followed by modifiers from the following list, and ends with a type
specifier. (Use '%%'
to get a
single percent character in the output.) The modifiers must appear
in the order in which they are listed here:
A padding specifier denoting the character to use to pad the results to the appropriate string size. Specify
0
, a space, or any character prefixed with a single quote. Padding with spaces is the default.A sign. This has a different effect on strings than on numbers. For strings, a minus (
-
) here forces the string to be left-justified (the default is to right-justify). For numbers, a plus (+
) here forces positive numbers to be printed with a leading plus sign (e.g.,35
will be printed as+35
).The minimum number of characters that this element should contain. If the result is less than this number of characters, the sign and padding specifier govern how to pad to this length.
For floating-point numbers, a precision specifier consisting of a period and a number; this dictates how many decimal digits will be displayed. For types other than double, this specifier is ignored.
Type specifiers
The type specifier tells printf(
)
what type of data is being substituted. This determines
the interpretation of the previously listed modifiers. There are
eight types, as listed in Table 4-2.
Specifier | Meaning |
| The argument is an integer and is displayed as a binary number. |
| The argument is an integer and is displayed as the character with that value. |
| The argument is an integer and is displayed as a decimal number. |
| The argument is a double and is displayed as a floating-point number. |
| The argument is a double with precision and is displayed as a floating-point number. |
| The argument is an integer and is displayed as an octal (base-8) number. |
| The argument is a string and is displayed as such. |
| The argument is an unsigned integer and is displayed as a decimal number. |
| The argument is an integer and is displayed as a hexadecimal (base-16) number; lowercase letters are used. |
| The argument is an integer and is displayed as a hexadecimal (base-16) number; uppercase letters are used. |
The printf( )
function
looks outrageously complex to people who aren’t C programmers. Once
you get used to it, though, you’ll find it a powerful formatting
tool. Here are some examples:
A floating-point number to two decimal places:
printf('%.2f', 27.452);
27.45
Decimal and hexadecimal output:
printf('The hex value of %d is %x', 214, 214);
The hex value of 214 is d6
Padding an integer to three decimal places:
printf('Bond. James Bond. %03d.', 7);
Bond. James Bond. 007.
Formatting a date:
printf('%02d/%02d/%04d', $month, $day, $year);
02/15/2005
A percentage:
printf('%.2f%% Complete', 2.1);
2.10% Complete
Padding a floating-point number:
printf('You\'ve spent $%5.2f so far', 4.1);
You've spent $ 4.10 so far
The sprintf( )
function
takes the same arguments as printf(
)
but returns the built-up string instead of printing it.
This lets you save the string in a variable for later use:
$date = sprintf("%02d/%02d/%04d", $month, $day, $year); // now we can interpolate $date wherever we need a date
print_r( ) and var_dump( )
The print_r( )
construct intelligently displays what is passed to it, rather than
casting everything to a string, as echo
and print(
)
do. Strings and numbers are simply printed. Arrays appear
as parenthesized lists of keys and values, prefaced by Array
:
$a = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma'); print_r($a); Array ( [name] => Fred [age] => 35 [wife] => Wilma)
Using print_r( )
on an array
moves the internal iterator to the position of the last element in the
array. See Chapter 5 for more on
iterators and arrays.
When you print_r( )
an
object, you see the word Object
,
followed by the initialized properties of the object displayed as an
array:
class P { var $name = 'nat'; // ... } $p = new P; print_r($p); Object ( [name] => nat)
Boolean values and NULL
are
not meaningfully displayed by print_r(
)
:
print_r(true); // prints "\n"; 1 print_r(false); // prints "\n"; print_r(null); // prints "\n";
For this reason, var_dump( )
is preferred over print_r( )
for
debugging. The var_dump( )
function
displays any PHP value in a human-readable format:
var_dump(true); bool(true) var_dump(false); bool(false); var_dump(null); bool(null); var_dump(array('name' => Fred, 'age' => 35)); array(2) { ["name"]=> string(4) "Fred" ["age"]=> int(35) } class P { var $name = 'Nat'; // ... } $p = new P; var_dump($p); object(p)(1) { ["name"]=> string(3) "Nat" }
Beware of using print_r( )
or
var_dump( )
on a recursive
structure such as $GLOBALS
(which
has an entry for GLOBALS
that
points back to itself). The print_r(
)
function loops infinitely, while var_dump( )
cuts off after visiting the same
element three times.
Get Programming PHP, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.