php printf statement

The printf() statement is ideal when you want to output a blend of static text and dynamic information stored within one or several variables.

It's ideal for two reasons. First, it neatly separates the static and dynamic data into two distinct sections, allowing for easy maintenance.

Second, printf() allows you to wield considerable control over how the dynamic information is rendered to the screen in terms of its type, precision, alignment, and position. Its prototype looks like this:

printf syntax :

boolean printf ( string format [, mixed args] )

For example, suppose you wanted to insert a single dynamic integer value into an otherwise static string:

printf example :


printf ( "Bar inventory: %d bottles of tonic water.", 100 );

Executing this command produces the following:

Out put :

Bar inventory: 100 bottles of tonic water.

In this example, %d is a placeholder known as a type specifier, and the d indicates an integer value will be placed in that position. When the printf() statement executes, the lone argument, 100, will be inserted into the placeholder. Remember that an integer is expected, so if you pass along a number including a decimal value (known as a float), it will be rounded down to the closest integer. If you pass along 100.2 or 100.6, 100 will be output. Pass along a string value such as "one hundred", and 0 will be output.

Type Description
%b Argument considered an integer; presented as a binary number
%c Argument considered an integer; presented as a character corresponding to that ASCII value
%d Argument considered an integer; presented as a signed decimal number
%f Argument considered a floating-point number; presented as a floating-point number
%o Argument considered an integer; presented as an octal number
%s Argument considered a string; presented as a string
%u Argument considered an integer; presented as an unsigned decimal number
%x Argument considered an integer; presented as a lowercase hexadecimal number
%X Argument considered an integer; presented as an uppercase hexadecimal number

So what do you do if you want to pass along two values? Just insert two specifiers into the string and make sure you pass two values along as arguments. For example, the following printf() statement passes in an integer and float value:

printf("%d bottles of tonic water cost $%f", 100, 43.20);

Executing this command produces the following:

Out put :

100 bottles of tonic water cost $43.20

When working with decimal values, you can adjust the precision using a precision specifier. An example follows:

printf("$%.2f", 43.2); // $43.20

Still other specifiers exist for tweaking the argument's alignment, padding, sign, and width. Consult the PHP manual for more information.





Content