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 Build a Simple PHP Application Listing Inventory Items Creating the Products Array

Aaron Munoz
Aaron Munoz
11,177 Points

How is the foreach statement creating <li> elements?

I've seen other methods where some will echo out a string with HTML tags inside but here, Randy embeds php inside an li element. How does it generate an li element for each pass?

2 Answers

Kevin Korte
Kevin Korte
28,148 Points

The list element tags are inside of the foreach block still, even though that PHP tag gets closed out. The PHP engine doesn't care when or where you open or close PHP tags, it's just going to look at the PHP syntax, and because the list element tag is inside of the block's closing curly brace, it's going to create a new list item on each loop iteration, ignoring but including everything in the block that is not in a php tag.

Aaron Munoz
Aaron Munoz
11,177 Points

And after further going through this course, it seems like it's better to echo your tags because of white-space issues. Am I correct?

Kevin Korte
Kevin Korte
28,148 Points

Meh, echo'ing HTML gets messy fast. If it's a single block of HTML like this

<?php
if(no_error) {
  echo '<div class="success">Great, no errors!</div>';
} else {
  echo '<div class="error">Sorry, there is an error!</div>';
}

than that is fine. But I'm not going to do something like this

<?php
if(no_error) {
  echo '<div class="' . $error_div_class . '" id = "' . $error_div_id . '">' . $error_title . '</div>';
} 

As you can see, it's easier to troubleshoot a whitespace error than it would be figure out an error in that cluster of single and double quotes and concatenation.

Aaron Munoz
Aaron Munoz
11,177 Points

Great stuff. Thanks Kevin.

Kevin Korte
Kevin Korte
28,148 Points

No problem. Happy I could help