代碼示例
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312">
<title>for 循環示例</title>
</head>
<body>
<h2 align="center">客戶端信息 - FOR 循環</h2>
<hr color="red">
<?php
echo "<table border=1>\n";
// 使用 for 循環遍歷 $GLOBALS
for ($key = reset($GLOBALS); $key = key($GLOBALS); $key = next($GLOBALS)) {
$value = current($GLOBALS); // pos() 是 current() 別名
echo "<tr><td>$key</td><td>$value</td></tr>\n";
}
echo "</table>\n";
?>
</body>
</html>
關鍵點解析
$GLOBALS 是包含所有全局變量的關聯數組,鍵為變量名。
reset() 將指針指向首元素並返回值;key() 返回當前鍵名;next() 移動指針到下一個;current() 返回當前值。
- 循環條件
$key = key($GLOBALS) 在鍵名為 0、""、null、false 時會提前結束,實際項目建議用 foreach ($GLOBALS as $key => $value) 更可靠。
現代寫法推薦
<?php
echo "<table border=1>";
foreach ($GLOBALS as $key => $value) {
// 避免遞歸輸出 $GLOBALS 自身導致無限循環
if ($key === 'GLOBALS') continue;
echo "<tr><td>" . htmlspecialchars($key) . "</td><td>" . htmlspecialchars(print_r($value, true)) . "</td></tr>";
}
echo "</table>";
?>