Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,650 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,650 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.