Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Nancy Melucci
PLUS
Nancy Melucci
Courses Plus Student 36,143 Points

Use a php function to fill an html image tag and show the image

So I've been asked to do this. I have an image expressed as an array and I've tried pretty much every way I can think of to make the html tag accept the members of the array but nothing works excepts for super simple stuff I am sure the instructor is not interested in seeing. I've tried the exotic php functions (array_combine for example) and foreach/for loops. I got nothing. Does anyone have an idea about how to make this work. I never ask unless I've spent a few hours trying. I am still too much of a newbie. My code is below. I know it sucks.

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>You Need Arrays</title>

  <link rel="stylesheet" href="assignment4.css">

</head>

<body>
<?php

$fish = array("apipefish.jpg", "Seattle Aquarium Pipefish",  "342", "640");

?>```


<img src="$fish[0]", title="$fish[1]", height="$fish[2]", width="$fish[3]" />;


</body>
</html>

1 Answer

Craig Fender
Craig Fender
7,605 Points

It's been like two years since I used PHP, so I don't have the most elegant solution. The problem is that you're trying to reference the data inside your array, but the browser only sees the img tag and none of the data written in PHP. You need to escape that call to the img tag for PHP to write that out to the browser. One possible way to do that is using string concatenation within the <?php ... ?> call. Like this,

    <?php
        echo '<img src="' . $fish[0] . '" title="' . $fish[1] . '" height="' . $fish[2] . '" width="' . $fish[3] . '" />';
    ?>

I hope that helps. Again, I haven't used PHP in awhile.

*EDIT

Sorry, I would probably use a formatted string over string concatenation because it's easier to read and more convenient. You can do that as follows:

    <?php
        printf('<img src="%s" title="%s" height="%s" width="%s" />', $fish[0], $fish[1], $fish[2], $fish[3]);
    ?>

And that should give you the same result.

Nancy Melucci
Nancy Melucci
Courses Plus Student 36,143 Points

Hey it works. I'll wait it out a bit (because I don't know whether or not she wants something fancier) but at least I have something that shows the image.