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 trialBen Goldman
14,626 PointsConcatenation 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>";
}
?>
</ul>
' ' '
1 Answer
Bryan Knight
34,215 PointsBen,
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
$product
``` was left inside the quotations you would literally see $product instead of the value that the $product variable contains.....if that makes sense.
Ben Goldman
14,626 PointsBen Goldman
14,626 PointsThanks, 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?