-1

I'm trying to print some thumbnails using PHP. The problem is that I can't get the value of $thumbPath in the HTML. There is some little mistake that I can't see:

for($i=1;$i<19;$i++){
                $thumbPath="img/theme".$i.".jpg";
                $thumbId="t".$i;
                echo '<li><a href="#">';
                echo '<img src=$thumbPath id=$thumbId border="none"/>';
                echo '</a></li>';
            }
George
  • 2,050
  • 6
  • 26
  • 36

5 Answers5

3

Strings in single quotes do not parse variables. You either need to do this:

echo "<img src=$thumbPath id=$thumbId border=\"none\"/>";

or this:

echo '<img src='.$thumbPath.' id='.$thumbId.' border="none"/>';
MattBelanger
  • 5,280
  • 6
  • 37
  • 34
  • 1
    But also, for valid modern HTML, you'll want to wrap the attribute values in quotes, too. And bear in mind you won't need to backquote the double-quotes if you're using single quotes as the string delimiter. So I'd maybe suggest something like `"";` or `echo '';` (HTML attributes can be quoted with single or double quotes, whichever is more convenient.) – Matt Gibson Sep 15 '11 at 12:39
  • Actually if I were you, I'd wrap it in a sprintf(); that way you can define exactly what you are expecting and it looks neat and tidy, and can be formatted the way you wish. http://php.net/sprintf – DarkMantis Sep 15 '11 at 12:41
  • @Matt Gibson Ah, the escapes on the double quotes around none were a copy/paste error. Thanks for pointing that out. – MattBelanger Sep 15 '11 at 12:44
  • @MattBelanger No problem. I would still recommend adding quotes around the attribute values, though; though attributes don't *need* to be quoted in all HTML document types, it's still [considered good practice to put them in](http://stackoverflow.com/questions/6495310/do-you-quote-html5-attributes). – Matt Gibson Sep 15 '11 at 12:54
2

change

echo '<img src=$thumbPath id=$thumbId border="none"/>';

to

echo '<img src="'.$thumbPath.'" id="'.$thumbId.'" border="none"/>';
peko
  • 11,267
  • 4
  • 33
  • 48
2

Variables enclosed in single quotes don't evaluate to php assigned values.

Translated, using echo '$thumbPath' isn't the same as echo "$thumbPath".

N.B.
  • 13,688
  • 3
  • 45
  • 55
1
echo '<img src='.$thumbPath.' id='.$thumbId.' border="none"/>';

Single quotes in php don't evaluate embedded variables. Hope it helps.

geezmo
  • 161
  • 1
  • 3
  • 12
1

Personally I would do the following:

[echo s]printf('<img src="%s" id="%d" border="none" />', 
            $thumbPath, 
            $thumbId);

Obviously I wrapped the optional bits in the [] to show that you can echo sprintf() or just printf()

That way it looks nice and you can do exactly what you want with it. It's more secure too because the parameters which you are passing to the sprintf will be forced to be either a digit, string, float, etc.

Just an idea

DarkMantis
  • 1,510
  • 5
  • 19
  • 40