Returns a string produced according to the formatting string format.
The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().
Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:
A type specifier that says what type the argument data should be treated as. Possible types:
| % - a literal percent character. No argument is required. |
| b - the argument is treated as an integer, and presented as a binary number. |
| c - the argument is treated as an integer, and presented as the character with that ASCII value. |
| d - the argument is treated as an integer, and presented as a (signed) decimal number. |
| u - the argument is treated as an integer, and presented as an unsigned decimal number. |
| f - the argument is treated as a float, and presented as a floating-point number. |
| o - the argument is treated as an integer, and presented as an octal number. |
| s - the argument is treated as and presented as a string. |
| x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). |
| X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). |
As of PHP version 4.0.6 the format string supports argument numbering/swapping. Here is an example:
<?php
$format = "There are %d monkeys in the %s";
printf($format,$num,$location);
?>This might output, "There are 5 monkeys in the tree". But imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as:
<?php
$format = "The %s contains %d monkeys";
printf($format,$num,$location);
?>We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:
<?php
$format = "The %2\$s contains %1\$d monkeys";
printf($format,$num,$location);
?>An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:
<?php
$format = "The %2\$s contains %1\$d monkeys.
That's a nice %2\$s full of %1\$d monkeys.";
printf($format, $num, $location);
?>See also printf(), sscanf(), fscanf(), vsprintf(), and number_format().
<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?><?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"
?>| This HTML Help has been published using the chm2web software. |