| 代碼 | 問題 | 修正 |
in_array('foo', $arr) | 字符串 '0' 匹配 false/0/null | in_array('foo', $arr, true) |
array_merge($a, $b) | 數字鍵重建導致順序變化 | 用 $a + $b 或 array_replace |
array_unique($arr) | 保留鍵導致索引不連續 | array_values(array_unique($arr)) |
sort($arr) | 字符串數字 '10' < '2' | natsort($arr) 或 sort($arr, SORT_NATURAL) |
array_filter($arr) | 無回調默認移除 falsy 值 | 明確回調 fn($v) => $v !== '' |
現代管道寫法(PHP 8.1+)
$users = [
['name'=>'Alice','age'=>25,'active'=>true],
['name'=>'Bob','age'=>17,'active'=>false],
['name'=>'Carol','age'=>30,'active'=>true],
];
// 取得活躍成年用戶名,按年齡降序
$names = array_column(
array_filter($users, fn($u) => $u['active'] && $u['age'] >= 18),
'name'
);
// 或使用箭頭函數鏈(需自定義 pipe 函數或用 laravel collect)
// collect($users)->where('active', true)->where('age', '>=', 18)->sortByDesc('age')->pluck('name')->all();
熟練使用標準庫,少寫循環,代碼更簡潔、可讀、高效。
- 上一篇文章: PHP遞歸遍歷目錄並統計文件/子目錄數量:高效實現與優化建議
- 下一篇文章: PHP自定義 urlencode/urldecode:針對 AJAX 傳輸的輕量編碼方案
Copyright ©
程式碼之家 All Rights Reserved