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 Working With Functions Creating the Shirt Display Function

Concatenation in PHP Foreach Loop

I just have a couple of questions about the following code block from the Build A Simple PHP App lesson. First, I don't understand why each line has to be echoed. Why couldn't you just echo once for the complete code block? Also, why is concatenation used here? I'm confused why you couldn't run the code together instead of concatenating. Thanks!

' ' '

<ul class="products">
    <?php foreach($products as $product_id => $product) {
        echo "<li>"; 
        echo '<a href="shirt.php?id=' . $product_id . '">'; 
        echo '<img src="' . $product["img"] . '" alt="' . $product["name"] . '">';
        echo "<p>View Details</p>";
        echo "</a>";
        echo "</li>"; 

' ' '

1 Answer

Bryan Knight
Bryan Knight
34,214 Points


The multiple echo statements may be for readability purposes only. The concatenation is needed for the variables so that they are not literally echoed out as part of the string inside the quotations. If

``` was left inside the quotations you would literally see $product instead of the value that the $product variable contains.....if that makes sense.

Thanks, Bryan. That makes the concatenation a lot clearer. As for the echo statements, when you say "readability", do you mean so that it's easier for other programmers to read?