I use brackets when using foreach loops. What is endforeach for?
The endforeach keyword is used to close the code block of a foreach loop which was started using the foreach(...): syntax.
To terminate the control from any loop we need to use break keyword. The break keyword is used to end the execution of current for, foreach, while, do-while or switch structure.
The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With