PHP simple foreach loop with HTML

PhpHtmlForeach

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsys_debugView Question on Stackoverflow
Solution 1 - PhpilancoView Answer on Stackoverflow