Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf using the same values multiple times

Tags:

php

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

like image 551
jmenezes Avatar asked Nov 28 '13 08:11

jmenezes


Video Answer


2 Answers

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 %%";
like image 163
Barmar Avatar answered Oct 17 '22 07:10

Barmar


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 %%'
like image 33
deceze Avatar answered Oct 17 '22 06:10

deceze