| 函數 | 用途 | 回傳值 | 副作用 |
|---|---|---|---|
isset() | 檢查變數存在且非 null | true/false | 無 |
unset() | 銷毀變數,釋放記憶體 | 無 (void) | 變數不再存在 |
isset(mixed $var, mixed ...$vars): bool
true(短路求值)。__isset)。<?php
$a = "test";
$b = null;
$c = [];
echo isset($a) ? 'true' : 'false'; // true
echo isset($b) ? 'true' : 'false'; // false (null 視為未設定)
echo isset($c['key']) ? 'true' : 'false'; // false (鍵不存在)
echo isset($a, $c) ? 'true' : 'false'; // false ($c 為空陣列但存在,實際上 true,此處邏輯需注意)
// 修正:isset($a, $c) 兩者皆存在且非 null → true
?>
<?php
if (isset($_GET['id'], $_POST['action'])) {
// 兩個參數都存在且非空字串
}
?>
unset(mixed $var, mixed ...$vars): void
unset($a, $b, $c)。unset($arr['key']),陣列索引不會自動重排(需 array_values() 重建)。unset($obj->prop)。unset() 全域變數僅銷毀區域引用,需 global $var; unset($var) 或 unset($GLOBALS['var'])。<?php
$a = "test";
unset($a);
echo isset($a) ? 'true' : 'false'; // false
$arr = [1, 2, 3];
unset($arr[1]); // 移除值 2
print_r($arr); // [0 => 1, 2 => 3] 索引不連續
$arr = array_values($arr); // 重建索引 [0 => 1, 1 => 3]
?>
isset() 是檢查,唯讀操作;unset() 是修改,銷毀操作。isset($var) 為 true 時,unset($var) 後再次 isset($var) 為 false。isset() 可用於條件判斷;unset() 用於清理不需要的變數、釋放記憶體、移除陣列元素。<?php
$var = null;
isset($var); // false
array_key_exists('var', $GLOBALS); // true (變數存在但值為 null)
unset($var);
isset($var); // false
array_key_exists('var', $GLOBALS); // false (變數已從符號表移除)
?>
理解兩者差異,能避免「變數未定義」警告,並精確控制變數生命週期。