start page | rating of books | rating of authors | reviews | copyrights

Programming PHPProgramming PHPSearch this book

4.2. 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.

4.2.1. 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, though, by using the print( ) or printf( ) functions.

4.2.2. 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

4.2.3. 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 in. A % character in the format string indicates a substitution.

4.2.3.1. 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:

4.2.3.2. 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.

Table 4-2. printf( ) type specifiers

Specifier

Meaning

B

The argument is an integer and is displayed as a binary number.

C

The argument is an integer and is displayed as the character with that value.

d or I

The argument is an integer and is displayed as a decimal number.

e, E, or f

The argument is a double and is displayed as a floating-point number.

g or G

The argument is a double with precision and is displayed as a floating-point number.

O

The argument is an integer and is displayed as an octal (base-8) number.

S

The argument is a string and is displayed as such.

U

The argument is an unsigned integer and is displayed as a decimal number.

x

The argument is an integer and is displayed as a hexadecimal (base-16) number; lowercase letters are used.

X

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:

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

4.2.4. 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);       print "\n";
1
print_r(false);      print "\n";

print_r(null);       print "\n";

For this reason, var_dump( ) is preferable to 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.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.