Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

endforeach in loops?

I use brackets when using foreach loops. What is endforeach for?

like image 596
CyberJunkie Avatar asked Jan 05 '11 02:01

CyberJunkie


People also ask

Why use endforeach?

The endforeach keyword is used to close the code block of a foreach loop which was started using the foreach(...): syntax.

How to end foreach loop in php?

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.

What is the function of foreach construct in PHP?

The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.


1 Answers

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.

like image 63
Brad Mace Avatar answered Sep 18 '22 21:09

Brad Mace