The PHP Printf Function And Type Specifiers

The PHP Printf Function And Type Specifiers
The PHP printf( ) function works much like the print( ) function in that it outputs (prints) a string (argument) to the web browser. However, you will use the printf( ) function when you want to control how this argument will be formatted.

The printf( ) function must have as its first argument a special type of argument called a format string or format control string. This format control string contains the conversion specifications (instructions) for how to format the other arguments. There must be the same number of specifications as corresponding arguments. Lets take a look at an example of a printf( ) function that has two specifications in the format control string and two corresponding arguments.

printf("My age is %d. Next year I will be %d.", 21, 22);

My age is 21. Next year I will be 22.

There are three arguments for this printf( ) function. The first is the format control string and the second and third are corresponding arguments to be formatted. As you can see there are two conversion specifications in the format control string and the whole string is placed between quotation marks. Each specification begins with a %. They are both type specifiers, in this case the d type specifier, which will format the integers (21 and 22) as decimal numbers. There are other type specifiers that can be used to control how an argument is formatted. The chart below shows how these type specifiers format the same example argument (222).

Type SpecifiersDescriptionExample
222
dDisplays the integer argument as a decimal number222
bDisplays the integer argument as a binary number11011110
cDisplays the integer argument as a ASCII character equivalent
fDisplays the integer argument (double) as a floating-point number222.000000
oDisplays the integer argument as an octal number (base 8)336
sDisplays the integer argument as a string222
xDisplays the integer argument as a lowercase hexadecimal number (base 16)de
XDisplays the integer argument as a uppercase hexadecimal number (base 16)DE






This site needs an editor - click to learn more!



RSS
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.