endforeach in loops?
I use brackets when using foreach loops. What is endforeach for?
Solution 1:
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.
Solution 2:
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; ?>
Solution 3:
as an alternative syntax you can write foreach loops like so
foreach($arr as $item):
//do stuff
endforeach;
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; ?>
Solution 4:
It's just a different syntax. Instead of
foreach ($a as $v) {
# ...
}
You could write this:
foreach ($a as $v):
# ...
endforeach;
They will function exactly the same; it's just a matter of style. (Personally I have never seen anyone use the second form.)