icecube icecube - 1 month ago 10
PHP Question

Unable to properly understand vprintf() in PHP

I am unable to understand the following code:

$number = 123;
vprintf("With 2 decimals: %1\$.2f
<br>With no decimals: %1\$u",array($number));

Browser output:

With 2 decimals: 123.00
With no decimals: 123

But here there is only one element in array, whereas it has to be two arguments.

Also what is the meaning of

Answer Source

That's a way to specify which parameter you want to use. %1$s indicates the first parameter, %2$s the second, etc. It's a way of re-using a single parameter so you don't have to supply the same value multiple times in the function call:

$one = 'one';
$two = 'two';

printf('%s', $one); // 'one'
printf('%1$s', $one); // 'one'
printf('%s %s', $one, $two); // 'one two'
printf('%1$s %2$s', $one, $two); // 'one two'
printf('%2$s %1$s', $one, $two); // 'two one'

printf('%1$s %2$s %1$s', $one, $two); // 'one two one'

In your code, it's escaped with a \ because your format is in double quotes, which would try to parse a variable $.2f or $u (which don't exist) if the dollar sign is not escaped.