Can't understand vprintf () correctly in PHP
I cannot understand the following code:
<?php
$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 there is only one element in the array, whereas it must be two arguments.
Also what's the point %1\$
This is a way to specify which parameter you want to use. %1$s
indicates the first parameter, the %2$s
second, etc. This is a way to reuse the same parameter, so you don't need to specify the same value multiple times in a 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 was escaped with \
because your format is in double quotes, which will try to parse the variable $.2f
or $u
(which doesn't exist) if the dollar sign is not escaped.
source to share