PHP 是弱型別語言,執行期會根據上下文自動進行型別轉換(Type Juggling)。理解轉換規則能避免難以捉摸的邏輯錯誤(如 '' == 0 為 true)。本文系統整理布林值、數值、字串三大方向的轉換原則,並附對照表與實務建議。
以下值轉為 false,其餘皆為 true:
| 型別 | 值 | 備註 |
|---|---|---|
| Boolean | false | — |
| Integer | 0 | — |
| Float | 0.0 | — |
| String | '' (空字串)、'0' | 注意:'0.0' 為 true |
| Array | [] (空陣列) | — |
| NULL | null | — |
| Object | 無屬性的 SimpleXMLElement | 罕見情況 |
| 原始值 | 結果 | 規則說明 |
|---|---|---|
| 合法數字字串 (無 . e E) | Integer | 未超出整數範圍時 |
| 合法數字字串 (含 . e E) | Float | 或超出整數範圍 |
| 非數字開頭字串 | 0 | 如 'abc123' → 0 |
| true / false | 1 / 0 | — |
| null | 0 | — |
| Float → Integer | 向下取整 | (int)3.9 === 3 |
| 原始值 | 結果 | 備註 |
|---|---|---|
| Integer / Float | 數字字面值 | 如 123 → '123' |
| true / false | '1' / '' | false 變空字串 |
| null | '' | — |
| Array | 'Array' | 並不會輸出內容,且觸發 Notice |
| Resource | 'Resource id #N' | N 為資源編號 |
| Object | 呼叫 __toString() | 未實作則拋出 Error |
0 == '' // true 0 == '0' // true '0' == false // true '' == false // true '0.0' == false // false ← 易錯點 [] == false // true [] == '' // true
建議:嚴格比較 ===,或显式轉型 (bool)$val、(int)$val。
$x = '2text';
switch ($x) {
case 2: // '2text' == 2 為 true!
echo 'matched 2';
}
建議:case 值統一用字串,或改用 match (PHP 8+)。
echo 'Users: ' . $users; // Notice: Array to string conversion
建議:用 implode(',', $users)、json_encode($users) 或 print_r($users, true)。
string 含數字與 int 比較不再自動轉型('123' == 123 仍為 true,但 '123abc' == 123 現在為 false)。TypeError 而非 Warning。declare(strict_types=1); 模式下開發,強制標量型別宣告。熟練掌握自動轉換規則,並養成「嚴格比較、顯式轉型、啟用 strict_types」的習慣,能讓 PHP 程式碼更健壯、可預測。