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

Matt Borgman
Matt Borgman
18,313 Points

PHP String Interpolation

I am trying to better understand string interpolation when in comes to PHP. My question is why can you parse a variable with double quotes when it is by itself or within a string as follows:

$name = "Matt";
echo "My name is $name";

But, if you want to echo a string and HTML you have to use string concatenation, such as:

$name = "Matt";
echo "<h1>" . $name . "</h1>";

1 Answer

Hi Matt,

Your second example can be done the same way as the first example. Did you see something that suggested you couldn't do it?

Matt Borgman
Matt Borgman
18,313 Points

I'm trying to remember if I tried it previously and couldn't. What jogged my memory is on the PHP track, "Build a basic PHP website" course, the instructor does a foreach block as so:

    <ul>
      <?php 
      foreach($catalog as $item) {
        echo "<li>" . $item . "</li>";
      }
      ?>
    </ul>

But I tried it as you suggest and it worked both ways. If I did ever try the other way and have it not work it must have been a syntax error. Thank you for the response and helping me make sense of things.

There are some situations where you can't simply include the variable as in your examples. Your first example is considered simple syntax but there's a complex syntax where the variable has to be surrounded with curly braces.

You can read more about that here: http://php.net/manual/en/language.types.string.php#language.types.string.parsing

In the complex syntax section you'll see some examples of when you might need curly braces.

It will come in handy on this code challenge: https://teamtreehouse.com/library/php-arrays-and-control-structures/php-arrays/multidimensional-arrays

I'm not sure if you've taken that course already or plan to.

If you decide to use interpolation on that one then the curly braces will come in handy since it's a multi-dimensional array.

Matt Borgman
Matt Borgman
18,313 Points

Thank you for the further explanation and the resources, I will definitely check those out!