<?php
for ($i = 1, $n = 9; $i <= $n; $i++) {
if ($i == $n) {
echo "$i x $n = " . ($i * $n) . ' ';
$n = --$n;
$i = 1;
echo '<br>';
}
echo "$i x $n = " . ($i * $n) . ' ';
}
?>
輸出:
1 x 9 = 9 2 x 9 = 18 ... 9 x 9 = 81 1 x 8 = 8 ... 8 x 8 = 64 ... 1 x 1 = 1
<?php
for ($row = 1; $row <= 9; $row++) {
for ($col = 1; $col <= $row; $col++) {
echo "$col x $row = " . ($col * $row) . ' ';
}
echo '<br>';
}
?>
<table border="1" cellpadding="4" cellspacing="0">
<?php for ($i = 1; $i <= 9; $i++): ?>
<tr>
<?php for ($j = 1; $j <= $i; $j++): ?>
<td><?= $j ?> x <?= $i ?> = <?= $j * $i ?></td>
<?php endfor; ?>
</tr>
<?php endfor; ?>
</table>
| 寫法 | 行數 | 可讀性 | 效能 | 適用場景 |
|---|---|---|---|---|
| 單層迴圈 | 少 | 低(技巧性強) | 相同 | 程式競賽、展示技巧 |
| 雙層迴圈 | 中 | 高(直覺) | 相同 | 教學、實務開發 |
| 表格輸出 | 多 | 高 | 略多 HTML | 網頁呈現 |
function multiplicationTable(int $n = 9): string {
$html = '<table border="1" cellpadding="4">';
for ($i = 1; $i <= $n; $i++) {
$html .= '<tr>';
for ($j = 1; $j <= $i; $j++) {
$html .= "<td>$j x $i = " . ($j * $i) . "</td>";
}
$html .= '</tr>';
}
$html .= '</table>';
return $html;
}
echo multiplicationTable(12); // 12 階乘法表
原始來源:www.111cn.net