使用 HTML 的 PHP 简单 foreach 循环

我想知道是否最好写下面的例子:

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

所以基本上就是在 foreach 循环中嵌入 HTML,但是没有使用 echo来打印表标记。这能行吗?我知道在 JSP 中这是可行的。

201791 次浏览

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