The sprintf() function writes a formatted string to a variable.
string sprintf ( string $format [, mixed $args [, mixed $... ]] )
The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc.
Returns a string produced according to the formatting string format.
This will 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:
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:
An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:
When using argument swapping, the n$ position specifier must come immediately after the percent sign (%), before any other specifiers, as shown in the example below.
......123
000000123
%b = '10100111101010011010101101' %c = 'A' %d = '43951789' %e = '4.39518e+7' %u = '43951789' %u = '4251015507' %f = '43951789.000000' %o = '247523255' %s = '43951789' %x = '29ea6ad' %X = '29EA6AD' %+d = '+43951789' %+d = '-43951789'
[monkey] [ monkey] [monkey ] [0000monkey] [####monkey] [many monke]
Parameter | Description |
---|---|
format | Required. Specifies the string and how to format the variables in it. |
Possible format values: | |
Additional format values. These are placed between the % and the letter (example %.2f): | |
arg1 | Required. The argument to be inserted at the first %-sign in the format string |
arg2 | Optional. The argument to be inserted at the second %-sign in the format string |
arg++ | Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string |
Returns a string produced according to the formatting string format, or FALSE on failure.