7

I'm trying to use sprintf on a heredoc this way. It wont work. Any idea how to solve this?

$i = <<<EOD
This is your invoice for %1$s %1$s %1$s %1$s
EOD;

$year = '2013';

$i = sprintf($i,$year);

echo $i;

Notice: Undefined variable: s in

Gleb Kemarsky
  • 10,160
  • 7
  • 43
  • 68
jmenezes
  • 1,888
  • 6
  • 28
  • 44

2 Answers2

10

Because HEREDOC acts like a double-quoted string, PHP is attempting to interpolate the $s as a variable. Try NOWDOC instead

$i = <<<'EOD'
This is your invoice for %1$s %1$s %1$s %1$s
EOD;
Phil
  • 157,677
  • 23
  • 242
  • 245
4

Or just escape the dollar signs:

$i = <<<EOD
This is your invoice for %1\$s %1\$s %1\$s %1\$s
EOD;

This is useful e.g. in PHP 5.2 where there's no nowdoc syntax.

Martin Pecka
  • 2,953
  • 1
  • 31
  • 40