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 trialShafeeq Ahmed
6,058 PointsOne code inside two different PHP blocks
In the video https://teamtreehouse.com/library/php-basics/php-conditionals-loops/foreach-loops
Hampton opens a php block and writes an incomplete php code inside it and close that block after that he writes some html code and than he opens another php block and complete the incomplete code.
I don't understand the logic behind it. Is there any limitation for lines of gap between two php blocks that contains one code.
2 Answers
Matthew Bilz
15,829 PointsAs long as you close your curly braces somewhere on the page, there won't be an error. If you forget to close your curly brace (remember to open a php tag and close it, i.e.
<?php } ?>
you should be good to go without errors as long as the rest of your code is valid.
Benjamin Larson
34,055 PointsHi Shafeeq,
Just remember that that role of PHP here is to spit out HTML code. What is ultimately produced by a PHP script is pure HTML, and that is what is read by the browser.
There's more than 1 way to skin a cat when it comes to accomplishing this. Rather than opening and closing PHP blocks as Hampton did here:
<?php
foreach($social_icons as $icon) {
?>
<i><a href=""><span class="icon <?php echo $icon ?>"></span></a></li>
<?php
}
?>
He could have also used PHP to echo out the HTML and concatenated the string with the PHP variable, like this:
<?php
foreach($social_icons as $icon) {
echo '<i><a href=""><span class="icon' . $icon .'"></span></a></li>';
}
?>
It's probably less code to do it the second way, but the first way may give more cues with HTML syntax highlighting in a good text editor. There are still yet more ways to accomplish this, but just remember that the logic is not necessarily what is inside a specific PHP block, you may have to read more a script at times to figure out what is really being produced.