tags:

views:

60

answers:

1

I can't figure out how to say what I'm talking about which is a big part of why I'm stuck. In PHP I often see code like this

html
<?php
   language construct that uses brackets {
       some code;
?>
more html
<?php
       some more code;
    }
?>
rest of html

Is there any name for this? Having seen this lead me to try it out so here is a concrete example whose behavior doesn't make sense to me

<div id="content">
<ul id="nav">
<?php
    $path = 'content';
    $dir = dir($path);
    while(false !== ($file = $dir->read())) {
        if(preg_match('/.+\.txt/i', $file)) {
            echo "<li class=\"$file\">$file</li>";
?>
</ul>
<?php
            echo "<p class=\"$file\">" . file_get_contents($path . '/' . $file) . '</p>';
        }
    }
?>
</div>

Which outputs roughly <div><ul><li></li></ul><li></li><p></p>...</div> instead of <div><ul><li></li>...</ul><p></p>...</div>, which is what I thought would happen and what I want to happen. To make it clearer I want the <li> inside the <ul> and the <p> inside the <div>. Yes, I know there is an easy solution but I was wondering if there is a way to do it with the technique I am looking for a name for.

+3  A: 

Just something to add here:

If you're using a PHP loop for templating, there is another syntax that helps you avoid confusion with indentation and which-braces-match-which:

<?php
    foreach($items as $item):
?>
<b>item: </b> <?php echo $item; ?> <br />
<?php
    endforeach;
?>

this may be an oversimplification, but really you shouldn't be using anything more complicated than this in a template. Things like the $items variable and anything else you need should be set up by the code which includes the template, and not in the template itself.

Carson Myers
+1 for pointing out the alternative syntax that is made for templating.
Tim Lytle
That makes it entirely clear how to do what I was thinking, I should have the loop surrounding the div instead of inside of it. Still I hope I can get an explanation for how whatever I'm trying to talk about works.
Sandy Vanderbleek
how it works? You mean putting HTML between PHP blocks?When a PHP file is sent by a webserver to the PHP interpreter, the interpreter considers everything outside of <?php ?> to be output. In other words, it's like you just `echo`ed every line of it, but without the extra typing.
Carson Myers
Thank you! I see why what I was trying to do doesn't work. When it echoes the line out it does it only once so when the loop keeps going it isn't echoed again.
Sandy Vanderbleek
no, if you have some content inside of a loop, it will be output on each iteration of the loop -- see the example I put in the question: it should produce the output you would expect, a line of text for each `$item` in `$items`
Carson Myers
Oh true, thanks again, I'm silly, and couldn't see the invisible </ul> echoed every time. Now I understand exactly what was happening.
Sandy Vanderbleek
glad I could help :)
Carson Myers