I'm trying to use the same value in different places when using sprintf, but failing.
<?php
$score = 50;
$percent = 10;
$str = "Hello: You scored %s (%s%%). Your score is %2$s %%"; //Problem is here %2$s
echo sprintf($str,$score,$percent);
?>
I get this error: Notice: Undefined variable: s in C:\web\apache\htdocs\sprintf.php on line 6 Warning: sprintf(): Too few arguments in C:\web\apache\htdocs\sprintf.php on line 8
Use single quotes instead of double quotes:
$str = 'Hello: You scored %s (%s%%). Your score is %2$s %%';
Variables are expanded inside double quotes, so $s
was treated as a variable, not a formatting option.
If you want to use double quotes, you can escape the dollar sign:
$str = "Hello: You scored %s (%s%%). Your score is %2\$s %%";
A $
inside of double quoted strings is used for variable interpolation, PHP is looking for the variable $s
here. Use single quoted strings and number all your arguments while you're at it:
'Hello: You scored %1$s (%1$s%%). Your score is %2$s %%'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With