Formatting Strings with PHP

Until now, we have simply printed any strings that we want to display directly to the browser. PHP provides two functions that allow you first to apply formatting, whether to round doubles to a given number of decimal places, define alignment within a field, or display data according to different number systems. In this section, you will look at a few of the formatting options provided by printf() and sprintf().

Working with printf()

If you have any experience with C, you will be familiar with the printf() function. The PHP version is similar but not identical. printf() requires a string argument, known as a format control string. It also accepts additional arguments of different types. The format control string contains instructions indicating how to display these additional arguments. The following snippet, for example, uses printf() to output an integer as a decimal:

printf("This is my number: %d", 55);
// prints "This is my number: 55"


Within the format control string (the first argument), we have included a special code, known as a conversion specification.

A conversion specification begins with a percent (%) symbol and defines how to treat the corresponding argument to printf(). You can include as many conversion specifications as you want within the format control string, as long as you send an equivalent number of arguments to printf().

The following snippet outputs two numbers using printf():

printf("First number: %d<br>\nSecond number: %d<br>\n", 55, 66);
// Output:
// First number: 55
// Second number: 66

The first conversion specification corresponds to the first of the additional arguments to printf(), which is 55. The second conversion specification corresponds to 66. The d following the percent symbol requires that the data be treated as a decimal integer. This part of a conversion specification is a type specifier.

printf() and Type Specifiers

You have already come across one type specifier, d, which displays data in decimal format. Table 13.1 lists the other available type specifiers.

Table 13.1. Type Specifiers




Display argument as a decimal number


Display an integer as a binary number


Display an integer as ASCII equivalent


Display an integer as a floating-point number (double)


Display an integer as an octal number (base 8)


Display argument as a string


Display an integer as a lowercase hexadecimal number (base 16)


Display an integer as an uppercase hexadecimal number (base 16)

Listing 13.1 uses printf() to display a single number according to some of the type specifiers listed in Table 13.1.

Listing 13.1 Demonstrating Some Type Specifiers
  1: <html>
  2: <head>
  3: <title>Listing 13.1 Demonstrating some type specifiers</title>
  4: </head>
  5: <body>
  6: <?php
  7: $number = 543;
  8: printf( "Decimal: %d<br>", $number );
  9: printf( "Binary: %b<br>", $number );
 10: printf( "Double: %f<br>", $number );
 11: printf( "Octal: %o<br>", $number );
 12: printf( "String: %s<br>", $number );
 13: printf( "Hex (lower): %x<br>", $number );
 14: printf( "Hex (upper): %X<br>", $number );
 15: ?>
 16: </body>
 17: </html>

Put these lines into a text file called listing 13.1.php, and place this file in your Web server document root. When you access this script through your Web browser, it should look something like Figure 13.1. As you can see, printf() is a quick way of converting data from one number system to another and outputting the result.

Figure 13.1. Demonstrating conversion specifiers.


When you specify a color in HTML, you combine three hexadecimal numbers between 00 and FF, representing the values for red, green, and blue. You can use printf() to convert three decimal numbers between 0 and 255 to their hexadecimal equivalents:

$red = 204;
$green = 204;
$blue = 204;
printf( "#%X%X%X", $red, $green, $blue );
// prints "#CCCCCC"

Although you can use the type specifier to convert from decimal to hexadecimal numbers, you can't use it to determine how many characters the output for each argument should occupy. Within an HTML color code, each hexadecimal number should be padded to two characters, which would become a problem if we changed our $red, $green, and $blue variables in the preceding snippet to contain 1, for example. We would end up with the output "#111". You can force the output of leading zeros by using a padding specifier.

Padding Output with the Padding Specifier

You can require that output be padded by leading characters. The padding specifier should directly follow the percent sign that begins a conversion specification. To pad output with leading zeros, the padding specifier should consist of a zero followed by the number of characters you want the output to take up. If the output occupies fewer characters than this total, the difference will be filled with zeros:

printf( "%04d", 36 );
// prints "0036"

To pad output with leading spaces, the padding specifier should consist of a space character followed by the number of characters that the output should occupy:

printf( "% 4d", 36 )
// prints " 36"


A browser will not display multiple spaces in an HTML document. You can force the display of spaces and newlines by placing <PRE> tags around your output as follows:

print "The          spaces          will be visible";

If you want to format an entire document as text, you can use the header() function to change the Content-Type header:

header("Content-Type: text/plain");

Remember that your script must not have sent any output to the browser for the header() function to work as desired.

You can specify any character other than a space or a zero in your padding specifier with a single quotation mark followed by the character you want to use:

printf ( "%'x4d", 36 );
// prints "xx36"

We now have the tools we need to complete our HTML code example. Until now, we could convert three numbers, but we could not pad them with leading zeros:

$red = 1;
$green = 1;
$blue = 1;
printf( "#%02X%02X%02X", $red, $green, $blue );
// prints "#010101"

Each variable is output as a hexadecimal number. If the output occupies fewer than two spaces, leading zeros will be added.

Specifying a Field Width

You can specify the number of spaces within which your output should sit. The field width specifier is an integer that should be placed after the percent sign that begins a conversion specification (assuming that no padding specifier is defined). The following snippet outputs a list of four items, all of which sit within a field of 20 spaces. To make the spaces visible on the browser, we place all our output within a PRE element:

print "<pre>";
printf("%20s\n", "Books");
printf("%20s\n", "CDs");
printf("%20s\n", "Games");
printf("%20s\n", "Magazines");
print "</pre>";

Figure 13.2 shows the output of this snippet.

Figure 13.2. Aligning with field width specifiers.


By default, output is right-aligned within the field you specify. You can make it left-aligned by prepending a minus (?) symbol to the field width specifier:

printf("%-20s\n", "Left aligned");

Note that alignment applies to the decimal portion of any number that you output. In other words, only the portion before the decimal point of a double will sit flush to the end of the field width when right-aligned.

Specifying Precision

If you want to output data in floating-point format, you can specify the precision to which you want to round your data. This capability is particularly useful when you are dealing with currency. The precision identifier should be placed directly before the type specifier. It consists of a dot (.) followed by the number of decimal places to which you want to round. This specifier has an effect only on data that is output with the f type specifier:

printf( "%.2f", 5.333333 );
// prints "5.33"


In the C language, you can use a precision specifier with printf() to specify padding for decimal output. The precision specifier has no effect on decimal output in PHP. Use the padding specifier to add leading zeros to integers.

Conversion Specifications: A Recap

Table 13.2 lists the specifiers that can make up a conversion specification in the order that they would be included. Note that it is difficult to use both a padding specifier and a field width specifier. You should choose to use one or the other, but not both.

Table 13.2. Components of Conversion Specification




Padding specifier

Determines the number of characters that output should occupy, and the characters to add otherwise


Field width specifier

Determines the space within which output should be formatted


Precision specifier

Determines the number of decimal places to which a double should be rounded


Type specifier

Determines the data type that should be output


Listing 13.2 uses printf() to output a list of products and prices.

Listing 13.2 Using printf() to Format a List of Product Prices
  1: <html>
  2: <head>
  3: <title>Listing 13.2 Using printf() to format
  4:        a list of product prices</title>
  5: </head>
  6: <body>
  7: <?php
  8: $products = array("Green armchair"=>222.4,
  9:             "Candlestick"=>"4",
 10:             "Coffee table"=>80.6
 11:             );
 12: print "<pre>";
 13: printf("%-20s%23s\n", "Name", "Price");
 14: printf("%'-43s\n", "");
 15: foreach ($products as $key=>$val) {
 16:     printf( "%-20s%20.2f\n", $key, $val );
 17: }
 18: print("</pre>");
 19: ?>
 20: </body>
 21: </html>

We first define an associative array containing product names and prices on line 8. We open print a PRE element so that the browser will recognize our spaces and newlines. Our first printf() call on line 13 defines the following format control string:


The first conversion specification ("%-20s") uses a field width specifier of 20 characters, with the output left-justified. We use a string type specifier. The second conversion specification ("%23s") sets up a right-aligned field width. This printf() call will output our field headers.

Our second printf() function call on line 14 draws a line of - characters across a field of 43 characters. We achieve this result with a padding specifier, which adds padding to an empty string.

The final printf() call on line 16 is part of a foreach statement that loops through our product array. We use two conversion specifications. The first ("%-20s") prints the product name as a string left-justified within a 20-character field. The second conversion specification ("%20.2f") uses a field width specifier to ensure that output will be right-aligned within a 20-character field, and a precision specifier to ensure that the double we output is rounded to two decimal places.

Put these lines into a text file called listing13.2.php, and place this file in your Web server document root. When you access this script through your Web browser, it should look like Figure 13.3.

Figure 13.3. Products and prices formatted with printf().


Argument Swapping

As of PHP 4.0.6, it became possible to use the format control string to change the order in which the provided arguments are incorporated into output.

Imagine, for example, that you are printing dates to the browser. You have the dates in a multidimensional array and are using printf() to format the output:

$dates = array(
            array( 'mon'=> 12, 'mday'=>25, 'year'=>2001 ),
            array( 'mon'=> 5, 'mday'=>23, 'year'=>2000  ),
            array( 'mon'=> 10, 'mday'=>29, 'year'=>2001 )

$format = include( "local_format.php" );

foreach($dates as $date) {
    printf( "$format", $date['mon'], $date['mday'], $date['year'] );

In the preceding snippet, we get our format control string from an include file called local_format.php. Assume that this file contains only the following:

return "%02d/%02d/%d<br>";

In that case, our output will be in the format mm/dd/yyyy:


Imagine now that we are installing our script for a British site. In the United Kingdom dates are commonly presented with days before months (dd/mm/yyyy). The core code cannot be changed, but configuration files such as local_format.php can. Luckily, we can now alter the order in which the arguments are presented from within the format control code:

return "%2\$02d/%1\$02d/%3\$d<br>";

We can insert the argument number we are interested in after the initial percentage character that marks each conversion specification, followed by an escaped dollar ($) character. So, in the preceding snippet, we are demanding that the second argument be presented, followed by the first, followed by the third. The result is a list of dates in British format:


Storing a Formatted String

The printf() function outputs data to the browser, which means that the results are not available to your scripts. You can, however, use the function sprintf(), which works in exactly the same way as printf() except that it returns a string that you can then store in a variable for later use. The following snippet uses sprintf() to round a double to two decimal places, storing the result in $dosh:

$dosh = sprintf("%.2f", 2.334454);
print "You have $dosh dollars to spend";

A particular use of sprintf() is to write formatted data to a file. You can call sprintf() and assign its return value to a variable that can then be printed to a file with fputs().

    Part III: Getting Involved with the Code