PHP 技巧:5个让你代码更优雅的实用函数
在 PHP 开发中,掌握一些“冷门”但强大的函数能显著提升代码质量。下面分享5个实用技巧。
1. array_column() 快速提取二维数组某列
$users = [['id'=>1,'name'=>'Tom'], ['id'=>2,'name'=>'Jerry']];
$names = array_column($users, 'name'); // ['Tom', 'Jerry']
2. str_contains() 代替 strpos() !== false(PHP 8+)
if (str_contains($email, '@gmail.com')) {
// 更直观,无需记忆 !== 的坑
}
3. unpack() 解析二进制数据
处理接口二进制包时,一行代码解包:
$bin = "\x00\x01\x02\x03";
$data = unpack('n*', $bin); // 转为无符号短整型数组
4. 使用 match 替代 switch(PHP 8+)
$status = match ($code) {
200, 201 => 'success',
404 => 'not found',
default => 'unknown',
};
// 返回值、严格比较、无需 break
5. array_key_exists() 与 isset() 的区别
isset() 在值为 null 时返回 false,而 array_key_exists() 会正确判断键是否存在。需要区分时请用后者。
结语
善用这些函数,代码更短、意图更清晰。你还有哪些私藏技巧?欢迎讨论!