98

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.

3
  • 3
    The alternative control syntax might be even better, YMMV. Commented Apr 21, 2012 at 11:06
  • 5
    Maybe he has to pay for executing his code :). Commented Apr 21, 2012 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. Commented Sep 13, 2019 at 15:37

1 Answer 1

251

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

Sign up to request clarification or add additional context in comments.

1 Comment

or alternative instead of echo $key, you can use <td><?=$key?></td>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.