sprintf using the same values multiple times

php

Solution

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 %%";

Problem

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`

Original source