The printf()
function outputs message with specified format.
printf() takes a string argument called a format string, usually followed by one or more additional arguments containing the string or strings to format. It then outputs the result.
The format string contains ordinary text mixed with one or more conversion specifications. Each conversion specification requires an additional argument to be passed to printf().
The resulting formatted string is then displayed. Conversion specifications always start with a percent (%) symbol.
For example,
// Displays "Pi rounded to a whole number is: 3" printf( "Pi rounded to a whole number is: %d", M_PI );
In this example, "Pi rounded to a whole number is: %d" is the format string, and the "%d" within the string is a conversion specification.
Here's another example that uses multiple conversion specifications:
// Displays "2 times 3 is 6." printf( "%d times %d is %d.", 2, 3, 2*3 );
PHP printf() function has the following format.
int printf ( string format [, mixed argument [, mixed ...]] )
This function takes a variable number of parameters: the first parameter is a format string, followed by zero or other parameters of various types.
The format strings for printf() is listed as follows.
Format | Meaning |
---|---|
%% | A literal percent character; no matching parameter is required |
%b | Parameter is an integer; output it as binary |
%c | Parameter is an integer; output it as a character with that ASCII value |
%d | Parameter is a positive integer; output it as decimal |
%e | Scientific notation using a lowercase (e.g. 1.2e+2) |
%E | Scientific notation using a uppercase (e.g. 1.2E+2) |
%f | Parameter is a float; express it as a float |
%F | Floating-point number (not local settings aware) |
%g | shorter of %e and %f |
%G | shorter of %E and %f |
%o | Parameter is an integer; output it as octal |
%s | Parameter is a string; output it as a string |
%u | Unsigned decimal number (equal to or greather than zero) |
%x | Parameter is an integer; output it as hexadecimal with lowercase letters |
%X | Parameter is an integer; output it as hexadecimal with uppercase letters |
Additional format values are placed between the % and the letter (example %.2f):
Additional format | Meaning |
---|---|
+ | Forces both + and - in front of numbers. By default, only negative numbers are marked |
' | What to use as padding. Default is space. Must be used together with the width specifier. Example: %'q20s (this uses "q" as padding) |
- | Left-justifies the variable value |
[0-9] | Minimum width held of to the variable value |
.[0-9] | Number of decimal digits or maximum string length |
The multiple additional format values must be in the same order as above.
You can add characters to the left (by default) or the right of the formatted argument to pad it to a fixed width.
This is useful for adding leading zeros to a number, or horizontally align many strings by padding with spaces.
To add padding you insert a padding specifier into conversion specification, before the type specifier.
The padding specifier consists of either a zero to pad with zeros or a space character to pad with spaces, followed by the number of characters to pad the result out to. printf() then adds as many zeros or spaces as required to make the result the correct width.
For example, the following code displays various numbers, using leading zeros where necessary to ensure the result is always six digits long:
printf( "%06d \n", 123 ); // Displays "000123" printf( "%06d \n", 4567 ); // Displays "004567" printf( "%06d \n", 123456 ); // Displays "123456"
The padding specifier can add characters where required, but it never truncates the output. So printf ("%06d", 12345678 ) displays "12345678" , not "345678".
This example pads various strings using leading spaces to ensure that they're right - aligned:
printf( "% 15s\n", "Hi" ); printf( "% 15s\n", "Hello" ); printf( "% 15s\n", "Hello, world!" );
You can also leave out the zero or space and just specify a number, in which case printf() pads with spaces.
You're not limited to zeros and spaces. To use your own padding character, insert an apostrophe (') followed by the character instead of the zero or space:
printf( "%'#8s", "Hi" ); // Displays "######Hi"
If you want to add padding to the right rather than the left - so that the result is left-aligned rather than right-aligned, add a minus (-) symbol between the padding character and the width specifier:
printf( "%'#-8s", "Hi" ); // Displays "Hi######"
Padding behaves differently when using f or F to display a float.
When displaying floating - point numbers with the f or F type specifier, you can use a precision specifier to indicate how many decimal places to round the number to. To add a precision specifier, insert a period (.), followed by the number of decimal places to use, before the type specifier:
printf( "%f \n ", 123.4567 ); // Displays "123.456700" (default precision) printf( "%.2f \n ", 123.4567 ); // Displays "123.46" printf( "%.0f \n ", 123.4567 ); // Displays "123" printf( "%.10f \n ", 123.4567 ); // Displays "123.4567000000"
You can use a padding specifier with a precision specifier, in which case the entire number is padded to the required length including the digits after the decimal point, as well as the decimal point itself:
printf( "%.2f \n ", 123.4567 ); // Displays "123.46" printf( "%012.2f \n ", 123.4567 ); // Displays "000000123.46" printf( "%12.4f \n ", 123.4567 ); // Displays " 123.4567"
If you use a precision specifier when formatting a string, printf() truncates the string to that many characters:
printf( "%.8s\n", "Hello, world!" ); // Displays "Hello, w"
The order of the additional arguments passed to printf() must match the order of the conversion specifications within the format string.
Argument swapping can change the order of the conversion specifications without being able to change the order of the arguments.
We can specify which argument you want each conversion specification to refer to. After each percentage ( % ) symbol, add the position of the argument you want to refer to (1 is the first argument after the format string, 2 is the second, and so on) followed by a dollar ($) symbol.
Your value %2$s contains %3$d and %1$d.
Related functions:
Returns the length of the outputted string
Output string with printf
<?php//ww w . j a v a 2 s . c o m
$info = "example from java2s.com";
printf("There were %s.", $info);
$str1 = "Hello";
$str2 = "Hello world from java2s.com!";
printf("[%s]\n",$str1);
printf("[%8s]\n",$str1);
printf("[%-8s]\n",$str1);
printf("[%08s]\n",$str1);
printf("[%'*8s]\n",$str1);
printf("[%8.8s]\n",$str2);
?>
%s
means "string parameter," which means that
$info
will be treated as text in printf()
.
The code above generates the following result.
Output more than one value with printf
<?PHP
$foo = "PHP";
$bar = "java2s.com";
$baz = "has";
printf(" %s %s %s %s %s %s.", $foo, $bar, $foo, $bar, $baz, $foo);
?>
In the code above we have six %s
formatters and six
variables.
PHP replaces each %s
with parameter.
The code above generates the following result.
If you specify %d
but provide a float,
PHP will ignore the decimal part of the number.
<?PHP// ww w. j a va 2 s . c o m
$number = 123;
printf("123 in binary is: %b", $number);
printf("123 in hex is: %h", $number);
printf("123 as a string is: %s", $number);
$num1 = 123456789;
$num2 = -123456789;
$char = 50; // The ASCII Character 50 is 2
// Note: The format value "%%" returns a percent sign
printf("%%b = %b \n",$num1); // Binary number
printf("%%c = %c \n",$char); // The ASCII Character
printf("%%d = %d \n",$num1); // Signed decimal number
printf("%%d = %d \n",$num2); // Signed decimal number
printf("%%e = %e \n",$num1); // Scientific notation (lowercase)
printf("%%E = %E \n",$num1); // Scientific notation (uppercase)
printf("%%u = %u \n",$num1); // Unsigned decimal number (positive)
printf("%%u = %u \n",$num2); // Unsigned decimal number (negative)
printf("%%f = %f \n",$num1); // Floating-point number (local settings aware)
printf("%%F = %F \n",$num1); // Floating-point number (not local settings aware)
printf("%%g = %g \n",$num1); // Shorter of %e and %f
printf("%%G = %G \n",$num1); // Shorter of %E and %f
printf("%%o = %o \n",$num1); // Octal number
printf("%%s = %s \n",$num1); // String
printf("%%x = %x \n",$num1); // Hexadecimal number (lowercase)
printf("%%X = %X \n",$num1); // Hexadecimal number (uppercase)
printf("%%+d = %+d \n",$num1); // Sign specifier (positive)
printf("%%+d = %+d \n",$num2); // Sign specifier (negative)
?>
The code above generates the following result.
To output %
we use %%
.
<?PHP
printf("%% allows you to print percent characters");
?>
The code above generates the following result.
Revolving around the use of . (a period). For example:
<?PHP
$number = 123.456;
printf("Formatted number is %.2f\n", $number);
?>
%f
is the format term meaning float, preceding
the f
with .2
rounds the float to two
decimal places.
We could have used %.1f
for one decimal place,
%.8f
for eight decimal places, etc.
The code above generates the following result.
Output a formatted string:
<?php
$number = 9;
$str = "Beijing";
printf("There are %u million bicycles in %s.",$number,$str);
?>
The code above generates the following result.
Use of placeholders:
<?php
$number = 123;
printf("With 2 decimals: %1\$.2f
\nWith no decimals: %1\$u",$number);
?>
The code above generates the following result.
By default, printf() displays negative numbers with a minus (-) symbol in front of them, but doesn't put a plus (+) symbol in front of positive numbers.
To change printf()'s behavior so that it always displays a sign symbol, use the sign specifier , + , in front of the type specifier. Here's an example:
<?PHP
printf( "%d \n", 123 ); // Displays "123"
printf( "%d \n", -123 ); // Displays "-123"
printf( "%+d \n", 123 ); // Displays "+123"
printf( "%+d \n", -123 ); // Displays "-123"
?>
The code above generates the following result.