Formatting Strings

PHP provides a powerful way of creating formatted strings, using the printf and sprintf functions. If you have used this function in C, these will be quite familiar to you, although the syntax in PHP is a little different.

Using printf

You use printf to display a formatted string. At its very simplest, printf takes a single string argument and behaves the same as echo:

 printf("Hello, world"); 

The power of printf, however, lies in its ability to substitute values into placeholders in a string. Placeholders are identified by the percent character (%), followed by a format specification character.

The following example uses the simple format specifier %f to represent a float number.

 $price = 5.99; printf("The price is %f", $price); 

The second argument to printf is substituted in place of %f, so the following output is produced:

 The price is 5.99 

There is actually no limit to the number of substitution arguments in a printf statement, as long as there are an equivalent number of placeholders in the string to be displayed. The following example demonstrates this by adding in a string item:

 $item = "The Origin of Species"; $price = 5.99; printf("The price of %s is %f", $item, $price); 

Table 6.1 shows the format characters that can be used with the printf function in PHP to indicate different types of values.

Table 6.1. printf Format Characters




A binary (base 2) number


The ASCII character with the numeric value of the argument


A signed decimal (base 10) integer


A number displayed in scientific notation (for example, 2.6e+3)


An unsigned decimal integer


A floating-point number


An octal (base 8) number


A string


A hexadecimal (base 16) number with lowercase letters


A hexadecimal (base 16) number with uppercase letters

Suppose you use the %d format specifier instead of %f to display the value of $price:

 $price = 5.99; printf("As a decimal, the price is %d", $price); 

In this case, PHP will treat the argument passed as an integer, so only the whole part of the value will be displayed. The output produced is as follows.

 As a decimal, the price is 5 

Decimals The %d format string represents a decimal integer, with decimal referring to base 10 numbers and not decimal points. There are different format specifiers to display numbers in base 16 (hex, %x), base 8 (octal, %o), and base 2 (binary, %b).

Format Codes

A format specifier can also include optional elements to specify the padding, alignment, width, and precision of the value to be displayed. This allows you to carry out some very powerful formatting.

The width specifier indicates how many characters the formatted value should occupy in the displayed string and appears between the percent sign and the type specifier. For instance, the following example ensures that the name displayed takes up exactly 10 characters:

 $name1 = "Tom"; $name2 = "Dick"; $name3 = "Harry"; echo "<PRE>"; printf("%10s \n", $name1); printf("%10s \n", $name2); printf("%10s \n", $name3); echo "</PRE>"; 

Padding These examples use <PRE> tags to make sure that multiple spaces used for padding are displayed onscreen. Usually a web browser will treat multiple adjacent whitespace characters as a single space.

String padding is not used very often in creating dynamic web pages. However, it is useful when you're producing plain-text output, such as generated email text, in PHP.

If you run this example through a web browser, you will see that each name displayed is indented from the left of the screen by the correct number of characters to make each name right-aligned with the others.

The default behavior is to right-align to the given width. However, you can reverse this by using the minus symbol as an alignment specifier. To left-align the strings in the previous example, you would use the format specifier %-10s. Although visibly this would not appear any different from simply using %s, the strings would be padded on the right with spaces to a length of 10 characters.

You can change the padding character from a space to any other character by placing that character before the width value, prefixed with a single quotation mark. The following example ensures that a five-digit order number is always displayed padded with zeros if necessary:

 $order = 201; printf("Order number: %'05d", $order); 

The output produced is as follows:

 Order number: 00201 

The precision specifier is used with a floating-point number to specify the number of decimal places to display. The most common usage is with currency values, to ensure that the two cent digits always appear, even in a whole dollar amount.

The precision value follows the optional width specifier and is indicated by a period followed by the number of decimal places to display. The following example uses %.2f to display a currency value with no width specifier:

 $price = 6; printf("The price is %.2f", $price); 

The price is correctly formatted as follows:

 The price is 6.00 

Float Widths With floats, the width specifier indicates only the width of the number before the decimal point. For example, %6.2f will actually be nine characters long, with the period and two decimal places.

Using sprintf

The sprintf function is used to assign formatted strings to variables. The syntax is the same as for printf, but rather than being output as the result, the formatted value is returned by the function as a string.

For example, to assign a formatted price value to a new variable, you could do the following:

 $new_price = sprintf("%.2f", $price); 

All the format specifier rules that apply to printf also apply to sprintf.

    Sams Teach Yourself PHP in 10 Minutes
    Sams Teach Yourself PHP in 10 Minutes
    ISBN: 0672327627
    EAN: 2147483647
    Year: 2005
    Pages: 151
    Authors: Chris Newman

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: