How to Repeat Arguments in PHP's sprintf Function?

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:


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.

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.