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

Why do we use concatenation when outputting this img tag with PHP?

I don't fully understand why we are using concatenation in this code when using PHP to output the HTML img tag.

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

If I were to write the code myself I would think to write it in the format below but I tested it and that doesn't work.

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

I know this must be something simple that I'm just not understanding fully yet.

4 Answers

Drew,

Not exactly. Lets see if I can walk you through this with an example:

If we are simply assigning a string, or set of characters, to a variable then (as far as I know) you can use single or double quotes interchangeably.

```$var1 = 'This is a string'; $var2 = "This is a string';

$var1 and $var2 are equivalent values.

Now, if we are talking output to the browser, PHP is going to treat single and double quotes a little differently:

Here is the important thing to remember - single quotes will display everything inside them as is and NOT output your variables. 

```echo '$var1;'```

The output to the browser would read: *$var1*

Whereas double quotes will evaluate variables:

```echo "$var1;"```

The output to the browser would read: *This is a string*

Here is a good site for further reading: http://www.scriptingok.com/tutorial/Single-quotes-vs-double-quotes-in-PHP

Drew,

You need to use concatenation because you're combining two different data types - strings and variables.

You're second example would output '$product' exactly as it is written because there are no breaks after the opening single quote so the complier reads it as one long string.

Whereas the first example, it reads a string, then a variable, then another string, etc...

Does that help?

That helps a little more. I think it's the single quote marks that are confusing me.

Is the purpose of the single quotes to let the server know there is PHP code within them that needs to be executed? If we didn't have them, then no code would execute and everything within the double quotes would be treated as a string?

Thank you! I forgot that single and double quotes are treated differently when not assigning a variable. It makes much more sense now.