存取陣列不存在的鍵 (如 $_GET['id']、$arr[5]) 時,PHP 會發出 E_NOTICE:Notice: Undefined index: ... 或 Undefined offset: ...。這不影響執行但汙染日誌、洩露結構,應妥善處理。
; php.ini error_reporting = E_ALL & ~E_NOTICE
<?php error_reporting(E_ALL ^ E_NOTICE); // 關閉 Notice // 或 error_reporting(E_ALL & ~E_NOTICE); ?>
<?php $id = isset($_GET['id']) ? $_GET['id'] : ''; // 或 PHP 7+ $id = $_GET['id'] ?? ''; ?>
<?php
if (empty($_POST['username'])) {
echo '請輸入用戶名';
}
?>
empty() 不會觸發 Notice,適合表單驗證。<?php
$data = ['name' => null];
isset($data['name']); // false (值為 null)
array_key_exists('name', $data); // true
?>
<?php
function get($array, $key, $default = '') {
return isset($array[$key]) ? $array[$key] : $default;
}
// 使用
$id = get($_GET, 'id');
$name = get($_POST, 'name', 'Guest');
?>
error_reporting(E_ALL),**修正所有 Notice**。display_errors=Off、log_errors=On,記錄至檔案。?? 或 isset() 提供預設值**,避免直接存取超全域陣列。empty() 檢查必填欄位。isset()/array_key_exists() 確認鍵存在。$arr[$key] ??= $default (空合併賦值) 確保鍵存在。@$_GET['id'] 抑制錯誤:**極度低效**,且隱藏真實問題。$_GET['id'] 不存在會回傳 null — 實際會觸發 Notice 並回傳 null。