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
Matt Bloomer
10,608 PointsPhp tags
I am doing the for each lesson in php. I am confused by the start and stopping of individual php tags. Here is the code that I am referring to:
<?php
foreach($social_icons as $icon){
?>
<li><a href=""><span class="icon <?php echo $icon ?>"></span></a></li>
<?php
}
?>
Why do we have tags end in the middle of the code blocks? Why is there a tag just before and after the curly brace? Any help anyone can give on this topic would be greatly appreciated/
2 Answers
Kevin Korte
28,149 PointsThe php parser is only going to look at what is in the php tags. Php tags can be opened and closed wherever, php really doesn't care.
Even though the html is outside of the php tags (as it has to be), it falls inside the foreach loop block. The php parser isn't' going to do anything with the html, but it does know it's there. So when PHP generates the html needed for the browser, it's going to repeat that bit of html however many time the foreach loop runs. All of the php will eventually get evaluated to html, and that's what the browser gets.
This bit of code would let you have a dynamically changing length of a list.
elk6
22,916 PointsHi Matt,
HTML and PHP can be mixed through each other. The first curly brace is inside the first php tags providing the foreach loop. Then, it needs to run some HTML, so you end the php and provide the HTML needed. But, this means that there is still an unclosed foreach loop. So, you open a php tag again, provide the closing curly brace to close the for each loop and close the php tag again to switch back to HTML.
Hope this makes it a bit clear.
Basically, when you want to do some php, you use the
<?php
//some code to run
?>
As soon as you close it you switch back to regular html.