| 函數 | 用途 | 返回類型 | 副作用 |
|---|---|---|---|
| isset() | 判斷變量是否已聲明且非 null | bool | 無 |
| empty() | 判斷變量是否為「空值」 | bool | 無 |
| is_null() | 判斷變量是否嚴格等於 null | bool | 無 |
| unset() | 銷毀變量 | void | 變量消失 |
以下值均被視為「空」 → empty() 返回 true:
""(空字符串)0(整數零)"0"(字符串零)0.0(浮點零)false(布爾假)[] / array()(空數組)null| 變量狀態 | empty() | is_null() | isset() |
|---|---|---|---|
| $a = "" | true | false | true |
| $a = null | true | true | false |
| unset $a | true | true | false |
| $a = [] | true | false | true |
| $a = false | true | false | true |
| $a = 15 | false | false | true |
| $a = 1 | false | false | true |
| $a = 0 | true | false | true |
| $a = "0" | true | false | true |
| $a = "true" | false | false | true |
| $a = "false" | false | false | true |
<?php
// ✅ 推薦:isset 判斷鍵是否存在
if (isset($_GET['id'])) { $id = (int)$_GET['id']; }
// ❌ 避免:empty 會誤判 id=0 為未提交
if (!empty($_GET['id'])) { ... } // id=0 時不進入!
?>
<?php
// ✅ 推薦:isset + 非 null 判斷
if (isset($config['debug']) && $config['debug'] !== null) { ... }
// ❌ empty 會誤判 false/0 為「未設置」
?>
<?php // PHP 7+ 零合併運算符(最優雅) $value = $arr['key'] ?? 'default'; // 兼容老版本 $value = isset($arr['key']) ? $arr['key'] : 'default'; ?>
<?php
// 只有 array_key_exists 能區分
$arr = ['key' => null];
isset($arr['key']); // false
array_key_exists('key', $arr); // true
?>
empty($obj->prop) 會觸發 __get() 魔術方法isset($arr['key']) 不會觸發數組言取錯誤,極其安全is_null() 參數必須是變量,is_null(func()) 會報錯(PHP 7.2+ 棄用)isset($GLOBALS['var']) 而非 isset($var)記住:isset 檢存在,empty 檢假值,is_null 檢純 null,unset 幹掉它 —— 選對工具,少寫 Bug。