2

How do you insert a printf comment inside of an echo? I have been trying to figure it out for the past hour and everything I try results in a different error.

Below is the last version of the code that I tried.

<?php
$i = 0;
do {
    echo "<li><a class=\"th radius\" href=\"img/coolstuff/" . printf("%03d", $i); . ".jpg\"><img src=\"img/coolstuff/" . printf("%03d", $i); . ".jpg\"></a></li>";
    $i++;
} while ($i < 282);
?>
unu
  • 195
  • 1
  • 3
  • 13

3 Answers3

2

Remove the ; before the ., otherwise you're terminating the statement.

Additionally, printf directly outputs the string, which will make it appear at the start of the outputted string. You want sprintf instead.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

Use sprintf() instead. It returns the formatted string instead of outputting it.

Also, as @Kolink mentioned, remove the semicolons, so your echo would look like this:

echo "<li><a class=\"th radius\" href=\"img/coolstuff/" . sprintf("%03d", $i) . ".jpg\"><img src=\"img/coolstuff/" . sprintf("%03d", $i) . ".jpg\"></a></li>";
Michal M
  • 9,322
  • 8
  • 47
  • 63
0

Do like this:

echo "<li><a class=\"th radius\" href=\"img/coolstuff/" , printf("%03d", $i);

Notice the comma , instead of dot ..

When using a comma with a echo statement, like above, each part is evaluated first. Atleast according to this accepted anwer.

Community
  • 1
  • 1
Daniel Figueroa
  • 10,348
  • 5
  • 44
  • 66