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 a C-like programming language, you will be familiar with the printf() function. The PHP version is similar but not identical to the C function. The PHP printf() function requires a string argument, known as a
format control string . It also accepts additional arguments of different types. The format control string contains instructions as to how to display these additional arguments. The following fragment, 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 fragment 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 8.1 lists the other type specifiers that are available.
Listing 8.1 uses printf() to display a single number according to some of the type specifiers listed in Table 8.1.
Notice that we do not only add conversion specifications to the format control string. Any additional text we include will be printed.
Listing 8.1 Demonstrating Some Type Specifiers
1: <html>
2: <head>
3: <title>Listing 8.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 listing8.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 8.1. As you can see, printf() is a quick way of converting data from one number system to another and outputting the result.
Figure 8.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 previous fragment to contain 1, for example. We would end up with the output "#111". You can force the output of leading zeroes 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 zeroes, 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 zeroes:
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"
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 zeroes:
$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 zeroes 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 fragment 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.
echo "<pre>";
printf("%20s\n", "Books");
printf("%20s\n", "CDs");
printf("%20s\n", "Games");
printf("%20s\n", "Magazines");
echo "</pre>";
Figure 8.2 shows the output of this fragment.
Figure 8.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 is particularly useful when 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 only has an effect on data that is output with the f type specifier:
printf("%.2f", 5.333333);
// prints "5.33"
Conversion Specifications: A Recap
Table 8.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.
Name | Description | Example |
---|---|---|
Padding specifier | Determines the number of characters that output should occupy, and the characters to add otherwise | '' 4'' |
Field width specifier | Determines the space within which output should be formatted | ''20'' |
Precision specifier | Determines the number of decimal places to which a double should be rounded | ''.4'' |
Type specifier | Determines the data type that should be output | ''d'' |
Listing 8.2 uses printf() to output a list of products and prices.
Listing 8.2 Using printf() to Format a List of Product Prices
1: <html>
2: <head>
3: <title>Listing 8.2 Using printf() to format a list of product prices</title>
4: </head>
5: <body>
6: <?php
7: $products = array("Green armchair"=>"222.4",
8: "Candlestick"=>"4",
9: "Coffee table"=>80.6
10:);
11: echo "<pre>";
12: printf("%-20s%23s\n", "Name", "Price");
13: printf("%''-43s\n", ");
14: foreach ($products as $key=>$val) {
15: printf( "%-20s%20.2f\n", $key, $val );
16: }
17: echo "</pre>";
18: ?>
19: </body>
20: </html>
We first define an associative array containing product names and prices on line 7. We open print a PRE element, so that the browser will recognize our spaces and newlines. Our first printf() call on line 12 defines the following format control string:
"%-20s%23s\n"
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 13 draws a line of - characters across a field of 43 characters. We achieve this with a padding specifier, which adds padding to an empty string.
The final printf() call on line 15 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 listing8.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 8.3.
Figure 8.3. Products and prices formatted with printf().

Argument Swapping
Imagine that you are printing dates to the browser. You have the dates in a multidimensional array and you are using printf() to format the output.
<?php
$dates = array(
array(''mon''=> 12, ''mday''=>25, ''year''=>2002),
array(''mon''=> 5, ''mday''=>23, ''year''=>2003),
array(''mon''=> 10, ''mday''=>29, ''year''=>2002)
);
$format = include("local_format.php");
foreach($dates as $date) {
printf("$format", $date[''mon''], $date[''mday''], $date[''year'']);
}
?>
In the preceding snippet, we are getting our format control string from an include file called local_format.php. Assuming that this file contains only
<?php
return "%02d/%02d/%d<br>";
?>
Our output will be in the format mm/dd/yyyy.
12/25/2002
05/23/2003
10/29/2002
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 our fragment, 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.
25/12/2002
23/05/2003
29/10/2002
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 fragment uses sprintf() to round a double to two decimal places, storing the result in $dosh:
$dosh = sprintf("%.2f", 2.334454);
echo "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().