九九乘法表是程式入門經典練習,涵蓋巢狀迴圈、字串格式化、條件判斷、表格輸出等核心概念。本文提供四種 PHP 實作風格,從基礎到進階,適合教學示範與面試熱身。
<?php
echo "<table border='1' cellpadding='5' cellspacing='0'>\n";
for ($i = 1; $i <= 9; $i++) {
echo " <tr>\n";
for ($j = 1; $j <= 9; $j++) {
$product = $i * $j;
// 對齊:個位數前補空格
$display = sprintf('%2d', $product);
echo " <td>$i × $j = $display</td>\n";
}
echo " </tr>\n";
}
echo "</table>\n";
<?php
echo "<table border='1' cellpadding='5' cellspacing='0'>\n";
for ($i = 1; $i <= 9; $i++) {
echo " <tr>\n";
for ($j = 1; $j <= $i; $j++) { // j <= i 只輸出左下三角
echo " <td>$j × $i = " . sprintf('%2d', $j * $i) . "</td>\n";
}
echo " </tr>\n";
}
echo "</table>\n";
<?php
/**
* 產生乘法表 HTML
*
* @param int $max 最大乘數(預設 9)
* @param bool $triangular true=三角形, false=完整方陣
* @param string $tableClass CSS 類別
* @return string HTML 字串
*/
function multiplicationTable(int $max = 9, bool $triangular = false, string $tableClass = 'multiplication-table'): string
{
$html = ["<table class='$tableClass'>"];
for ($i = 1; $i <= $max; $i++) {
$html[] = " <tr>";
$end = $triangular ? $i : $max;
for ($j = 1; $j <= $end; $j++) {
$product = $i * $j;
$html[] = " <td>$i × $j = " . sprintf('%2d', $product) . "</td>";
}
// 三角形模式補齊空白欄位(可選)
if ($triangular && $i < $max) {
$html[] = str_repeat(" <td> </td>", $max - $i);
}
$html[] = " </tr>";
}
$html[] = "</table>";
return implode("\n", $html);
}
// 使用
echo multiplicationTable(9, false, 'full-table'); // 完整 9x9
echo multiplicationTable(9, true, 'tri-table'); // 三角形
<?php
// api/multiplication.php
header('Content-Type: application/json; charset=UTF-8');
$max = (int)($_GET['max'] ?? 9);
$format = $_GET['format'] ?? 'grid'; // grid | triangular | flat
$data = [];
for ($i = 1; $i <= $max; $i++) {
for ($j = 1; $j <= $max; $j++) {
if ($format === 'triangular' && $j > $i) continue;
$data[] = [
'multiplicand' => $i,
'multiplier' => $j,
'product' => $i * $j,
'expression' => "$i × $j = " . ($i * $j),
];
}
}
echo json_encode([
'max' => $max,
'format' => $format,
'count' => count($data),
'data' => $data,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
<!-- 前端 Vue 3 範例 -->
<div id="app">
<select v-model="max">
<option v-for="n in 12" :value="n">{{ n }} × {{ n }}</option>
</select>
<label><input type="checkbox" v-model="triangular"> 三角形</label>
<table class="table">
<tr v-for="row in grouped" :key="row[0].multiplicand">
<td v-for="cell in row" :key="cell.multiplier">
{{ cell.expression }}
</td>
</tr>
</table>
</div>
<script type="module">
import { createApp, ref, computed } from 'vue'
createApp({
setup() {
const max = ref(9)
const triangular = ref(false)
const data = ref([])
async function load() {
const res = await fetch(`/api/multiplication.php?max=${max.value}&format=${triangular.value ? 'triangular' : 'grid'}`)
const json = await res.json()
data.value = json.data
}
const grouped = computed(() => {
const groups = {}
data.value.forEach(cell => {
if (!groups[cell.multiplicand]) groups[cell.multiplicand] = []
groups[cell.multiplicand].push(cell)
})
return Object.values(groups)
})
watch([max, triangular], load)
load()
return { max, triangular, grouped }
}
}).mount('#app')
</script>
<style>
.multiplication-table {
border-collapse: collapse;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
margin: 1rem auto;
}
.multiplication-table td {
border: 1px solid #ddd;
padding: 0.4rem 0.6rem;
text-align: right;
min-width: 4.5ch;
}
.multiplication-table tr:first-child td { background: #f8f9fa; font-weight: bold; }
.multiplication-table td:first-child { background: #f8f9fa; font-weight: bold; }
.multiplication-table td:nth-child(odd) { background: #fafafa; }
printf、sprintf、str_pad、number_formatimplode vs 輸出緩衝 ob_start九九乘法表雖小,卻能練習迴圈控制、資料結構、輸出格式化、函數封裝、前後端分離等完整開發技能。建議初學者從版本一入手理解邏輯,進階至版本三學習封裝與參數化,最終嘗試版本四體驗 API 設計與前端框架整合。程式設計的核心不在語法,而在於如何將問題分解、抽象、組合、驗證——這正是九九乘法表這類「玩具程式」的真正價值。