How to Repeat Arguments in PHP's sprintf Function?

Find out how to repeat or re-use an argument in the sprintf function in PHP

You can re-use or repeat an argument in PHP's sprintf, for example, like so:

echo sprintf('I found %1$d %2$s! Hello %2$s!', 10, 'ducks');

// output: "I found 10 ducks! Hello ducks!"

From the example above, you may have deduced that the format for re-using an argument in PHP's sprintf is as follows:

%[argnum$]specifier

Where argnum denotes the position of the argument you wish to re-use or repeat, and specifier denotes the type (from one of the following):

Specifier Treated As Presented As
d integer Signed decimal number
s string String
b integer Binary number
c integer ASCII
e scientific notation Scientific notation with lowercase "e" (e.g. 1.2e+2)
E scientific notation Scientific notation with uppercase "E" (e.g. 1.2E+2)
f float Floating-point number (locale aware)
F float Floating-point number (non-locale aware)
o integer Octal
u integer Unsigned decimal number
x integer hexadecimal number (with lowercase letters)
X integer hexadecimal number (with uppercase letters)

For example, %2$d would mean, "use the second argument after the string we need to format, and display it as a decimal number".

Use single quotes for the string you need to format, otherwise PHP will treat the specifier after the $ as a string.


Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.