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

  • By Daniyal Hamid
  • February 09, 2020
  • Comments
In This Article

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.


Did you find this article useful? Or do you have something to add to it? Please let us know in the comments section.