首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP while 迴圈進階應用:交替列色、多維表格、條件跳轉實戰

     編輯:PHP 相關知識

基礎語法回顧

while (條件) {
    // 迴圈主體
    // 需包含改變條件的邏輯,否則無限迴圈
}

案例一:產生 1000 筆資料的交替列色表格(單層迴圈)

<?php
echo '<table border="1" width="800" align="center">';
echo '<caption><h1>學生成績</h1></caption>';

$i = 0;
$rowCount = 0;
while ($i < 1000) {
    // 每 10 筆換行,並交替列色
    if ($i % 10 === 0) {
        if ($i > 0) echo '</tr>'; // 關閉上一行
        $bgColor = ($rowCount++ % 2 === 0) ? '#cccccc' : '#aaffaa';
        echo '<tr onmouseover="this.style.backgroundColor=\'red\'" onmouseout="this.style.backgroundColor=\'' . $bgColor . '\'" bgcolor="' . $bgColor . '">';
    }
    echo '<td>' . $i . '</td>';
    $i++;
}
echo '</tr></table>';
?>

<script>
var originalColor = null;
function highlight(row) {
    originalColor = row.style.backgroundColor;
    row.style.backgroundColor = 'red';
}
function restore(row) {
    row.style.backgroundColor = originalColor;
}
</script>

案例二:雙層迴圈產生 10x10 乘法表風格表格

<?php
echo '<table width="800" border="1" align="center">';
echo '<caption><h1>學生成績</h1></caption>';

$i = 0;
$k = 0;
while ($i < 100) {
    $bgColor = ($i % 2 === 0) ? '#cccccc' : '#aaffaa';
    echo '<tr onmouseover="highlight(this)" onmouseout="restore(this)" bgcolor="' . $bgColor . '">';

    $j = 0;
    while ($j < 10) {
        echo '<td>' . $k . '</td>';
        $j++;
        $k++;
    }
    echo '</tr>';
    $i++;
}
echo '</table>';
?>

案例三:IP 白名單條件跳轉(while 非典型用法)

<?php
$allowedIPs = ['127.0.0.1', '192.168.1.100'];
$clientIP = $_SERVER['REMOTE_ADDR'];

// 使用 while 模擬 do-while:至少檢查一次
$check = true;
while ($check) {
    $check = false; // 只執行一次
    if (in_array($clientIP, $allowedIPs)) {
        header('Location: admin.php');
    } else {
        header('Location: public.php');
    }
    exit;
}
?>

while 迴圈最佳實踐提醒

  • 永遠確保終止條件會變化:避免無限迴圈導致 PHP 超時(max_execution_time)
  • 大量資料輸出:考慮分頁、緩衝區(ob_start())、或改用生成器(yield)
  • 資料庫查詢結果遍歷:while ($row = $stmt->fetch()) 是標準模式
  • 檔案逐行讀取:while (($line = fgets($fp)) !== false)
  • 避免在迴圈內重複昂貴操作:如資料庫查詢、API 呼叫,應移至迴圈外或批次處理

對比:while vs for vs foreach

迴圈類型適用場景特點
while條件不明確、依賴外部狀態最靈活,需手動控制計數器
for已知迴圈次數、計數器明確結構緊湊,三段式初始/條件/遞增
foreach遍歷陣列/物件語法最簡潔,自動處理指標
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved