endforeach in loops? endforeach in loops? php php

endforeach in loops?


It's mainly so you can make start and end statements clearer when creating HTML in loops:

<table><? while ($record = mysql_fetch_assoc($rs)): ?>    <? if (!$record['deleted']): ?>        <tr>        <? foreach ($display_fields as $field): ?>            <td><?= $record[$field] ?></td>        <? endforeach; ?>        <td>        <select name="action" onChange="submit">        <? foreach ($actions as $action): ?>            <option value="<?= $action ?>"><?= $action ?>        <? endforeach; ?>        </td>        </tr>    <? else: ?>         <tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>    <? endif; ?><? endwhile; ?></table>

versus

<table><? while ($record = mysql_fetch_assoc($rs)) { ?>    <? if (!$record['deleted']) { ?>        <tr>        <? foreach ($display_fields as $field) { ?>            <td><?= $record[$field] ?></td>        <? } ?>        <td>        <select name="action" onChange="submit">        <? foreach ($actions as $action) { ?>            <option value="<?= $action ?>"><?= action ?>        <? } ?>        </td>        </tr>    <? } else { ?>         <tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>    <? } ?><? } ?></table>

Hopefully my example is sufficient to demonstrate that once you have several layers of nested loops, and the indenting is thrown off by all the PHP open/close tags and the contained HTML (and maybe you have to indent the HTML a certain way to get your page the way you want), the alternate syntax (endforeach) form can make things easier for your brain to parse. With the normal style, the closing } can be left on their own and make it hard to tell what they're actually closing.


It's the end statement for the alternative syntax:

foreach ($foo as $bar) :    ...endforeach;

Useful to make code more readable if you're breaking out of PHP:

<?php foreach ($foo as $bar) : ?>    <div ...>        ...    </div><?php endforeach; ?>


as an alternative syntax you can write foreach loops like so

foreach($arr as $item):    //do stuffendforeach;

This type of syntax is typically used when php is being used as a templating language as such

<?php foreach($arr as $item):?>    <!--do stuff --><?php endforeach; ?>