91

I am wondering if it will work best to actually write the following for example:

<table>
    <?php foreach($array as $key=>$value){ ?>
    <tr>
        <td><?php echo $key; ?></td>
    </tr>
    <?php } ?>
</table>

So basically embedding HTML inside foreach loop but without using echo to print the table tags. Will this work? I know in JSP this works.

Teun Zengerink
  • 4,277
  • 5
  • 30
  • 32
sys_debug
  • 3,883
  • 17
  • 67
  • 98
  • 3
    The [alternative control syntax](http://us.php.net/manual/en/control-structures.alternative-syntax.php) might be even better, YMMV. – DCoder Apr 21 '12 at 11:06
  • 5
    Maybe he has to pay for executing his code :). – kapa Apr 21 '12 at 11:27
  • 8
    It's not a useless question. This particular implementation is difficult to find in the PHP docs, and the accepted answer provides validation that it works without ten thousand developers needing to "just create a sample array and try" on an individual basis. – isherwood Sep 13 '19 at 15:37

1 Answers1

238

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Dharman
  • 30,962
  • 25
  • 85
  • 135
ilanco
  • 9,581
  • 4
  • 32
  • 37