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 Build a Simple PHP Application Listing Inventory Items Understanding Whitespace

Concatenation of the working variables. Why?

Can someone explain why there needs to be concatenation on each side of the working variable? What purpose does it serve?

Why won't this work?

echo '<img src="'$product["img"]'" alt="'$product["name"]'"';

Just curious. Thanks!

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Phillip,

Your current code is almost correct, after the opening single quote and before the ending single quote you need a period which tells the PHP compiler that you're joining two strings together, see the below.

NOTE: I've also added an ending closing bracket for the img element.

echo '<img src="' . $product["img"] . '" alt="' . $product["name"] . '">';

Now your code should work without any issues.

Happy coding!

Hi Chris,

I don't think you understood my question exactly, but I think you answered it anyway. The way that I understand it is that the single quotes are treating the HTML elements like a strings and the concatenation is joining the working PHP variable (which becomes a string) to HTML strings, which is why the working variables must be concatenated.

Chris Shaw
Chris Shaw
26,676 Points

Sorry, yes I did misunderstand slightly and yes that is what's happening, you can also include variables within strings using interpolation as well which is slightly cleaner but for most devs whom are new to PHP is harder to understand.

echo "<img src=\"{$product['img']}\" alt=\"{$product['name']\">";

One major different you will see if I've escaped the double quotes as PHP's version of interpolation requires double quotes to be surrounding the entire string, the other difference is instead of using double quotes to get the values in the $product array I've used single quotes as you can reuse double quotes if you're using interpolation.

Hope that helps.