Reputation: 3
I am making a quiz on a basic website using PHP and HTML/CSS and have answers stored in a PHP array.
I would like to display the quiz answers and the corresponding images (which I have named to match) using the simplest method. For example if $ANSWER="cat", I want to display "cat.jpg"
If it were possible to use a variable in the image URL it would be wonderful, but I haven't been able to find an example of this.
Should this syntax work?
echo '<img src=/pictures/"$ANSWER".jpg >';
So far I'm getting no output but not sure if it's due to a bug somewhere else.
Upvotes: 0
Views: 53
Reputation: 1464
Yes, try to use double quotes like:
echo "<img src='/pictures/".$ANSWER.".jpg' >";
or still use single quote like:
echo '<img src=\'/pictures/'.$ANSWER.'.jpg \'>';
Upvotes: 0
Reputation: 111
Hi :) Hope this helps :)
<?php
$ANSWER="cat";
?>
<img src="pictures/<?php echo "$ANSWER.jpg"; ?>">
Proven and tested :)
Upvotes: 0
Reputation: 2794
To expand on Rahul's answer:
PHP is server side meaning the page is not rendered until all of the PHP has resolved on the server.
That's why his answer works. The server gets
echo "<img src='/pictures/".$ANSWER.".jpg' />";
resolves $ANSWER to whatever the variable is set to and provides to the client side:
<img src='/pictures/my_answer.jpg' />
Upvotes: 1
Reputation: 1276
Simply
echo "<img src='/pictures/".$ANSWER.".jpg' >";
or
<img src="/pictures/<?php edho $ANSWER;?>.jpg">
Upvotes: 1