array — 数组类型
概述
array 是 PHP 中最强大、最常用的复合类型。PHP 的数组实际上是有序映射(ordered map),可以同时作为索引数组、关联数组和多维数组使用。数组在 PHP 中扮演着列表、集合、字典、栈、队列等多种数据结构的角色。
前置知识
在阅读本节之前,你需要了解:
- 变量的基本操作和赋值
- foreach 循环的基本用法
- 可空类型的概念
基础概念
PHP 数组的分类
PHP 数组
├── 索引数组:$colors = ['red', 'green', 'blue'];
├── 关联数组:$user = ['name' => 'Alice', 'age' => 30];
└── 多维数组:$matrix = [[1, 2], [3, 4]];语法与代码
数组创建与类型声明
php
<?php
declare(strict_types=1);
$fruits = ['apple', 'banana', 'cherry'];
$user = ['name' => 'Alice', 'email' => 'alice@example.com', 'age' => 30];
// PHP 7.3+ 尾部逗号
$data = ['a' => 1, 'b' => 2, 'c' => 3,];
function sum(array $numbers): int
{
return array_sum($numbers);
}
echo sum([1, 2, 3, 4, 5]); // 15常用数组操作
php
<?php
declare(strict_types=1);
// 添加
$arr = [];
$arr[] = 'a';
$arr['key'] = 'b';
array_push($arr, 'c');
// 访问
echo $arr[0];
echo $arr['missing'] ?? 'default';
// 删除
unset($arr[0]);
// 检查
echo isset($arr['key']);
echo in_array('b', $arr);
// 遍历
foreach ($arr as $value) { echo $value; }
foreach ($arr as $key => $value) { echo "{$key}: {$value}"; }
// 排序
sort($indexed);
asort($assoc);
usort($data, fn($a, $b) => $a['age'] <=> $b['age']);
// 函数式操作
$even = array_filter(range(1, 10), fn($n) => $n % 2 === 0);
$squares = array_map(fn($n) => $n ** 2, range(1, 5));
$sum = array_reduce(range(1, 5), fn($carry, $n) => $carry + $n, 0);
// 解构(PHP 7.1+)
[$a, $b, $c] = [1, 2, 3];
['name' => $name, 'age' => $age] = ['name' => 'Alice', 'age' => 30];
// 展开运算符(PHP 7.4+)
$all = [...[1, 2], ...[3, 4]]; // [1, 2, 3, 4]详细说明
数组元素类型
PHP 原生不支持泛型数组类型(如 array<int, string>),需要通过 PHPDoc 注释或 PHPStan 等工具约束。
数组与 iterable
array 是具体类型,iterable 是伪类型。iterable 可以接受数组和 Traversable 对象。
实战示例
集合工具类
php
<?php
declare(strict_types=1);
class ArrayCollection
{
private array $items;
public function __construct(array $items = [])
{
$this->items = $items;
}
public function map(callable $callback): self
{
return new self(array_map($callback, $this->items));
}
public function filter(callable $callback): self
{
return new self(array_filter($this->items, $callback));
}
public function first(callable $callback = null): mixed
{
if ($callback === null) return reset($this->items);
foreach ($this->items as $item) {
if ($callback($item)) return $item;
}
return null;
}
public function toArray(): array
{
return $this->items;
}
}
$users = new ArrayCollection([
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
]);
$names = $users->filter(fn($u) => $u['age'] >= 30)
->map(fn($u) => $u['name'])
->toArray();
echo implode(', ', $names); // Alice注意事项
数组比较
php
<?php
declare(strict_types=1);
[1, 2] == [2, 1]; // true(值相同即可)
[1, 2] === [2, 1]; // false(顺序不同)最佳实践
- 使用方括号语法:
['a']替代array('a') - 类型安全访问:使用
??运算符 - 使用解构:PHP 7.1+ 的列表语法
- array_map/filter/reduce:函数式处理
- 使用展开运算符:PHP 7.4+ 合并数组
下一节
下一节将详细介绍 object 对象类型。
进阶用法
调试与测试技巧
php
<?php
declare(strict_types=1);
// 单元测试辅助函数
function createTestResource(): mixed
{
return match (true) {
default => new stdClass(),
};
}
// 调试输出函数
function debugOutput(mixed , string = ''): void
{
= ? ": " : '';
.= print_r(, true);
fwrite(STDERR, . "\n");
}
// 性能基准测试
function benchmark(callable , int = 1000): float
{
= hrtime(true);
for ($i = 0; $i < $iterations; $i++) {
$fn();
}
return (hrtime(true) - $start) / 1e9;
}日志记录实践
php
<?php
declare(strict_types=1);
/**
* 简易日志记录器
*/
class SimpleLogger
{
private string $logFile;
private string $level = 'INFO';
public function __construct(string $logFile)
{
$this->logFile = $logFile;
}
public function info(string $message, array $context = []): void
{
$this->log('INFO', $message, $context);
}
public function warning(string $message, array $context = []): void
{
$this->log('WARNING', $message, $context);
}
public function error(string $message, array $context = []): void
{
$this->log('ERROR', $message, $context);
}
private function log(string $level, string $message, array $context): void
{
$timestamp = date('Y-m-d H:i:s');
$contextStr = $context ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
$line = "[{$timestamp}] [{$level}] {$message}{$contextStr}\n";
file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
}
}配置与环境检测
php
<?php
declare(strict_types=1);
// 环境检测工具
class EnvironmentChecker
{
public static function checkRequirements(array $requirements): array
{
$results = [];
foreach ($requirements as $name => $check) {
$results[$name] = is_callable($check) ? $check() : false;
}
return $results;
}
public static function getSystemInfo(): array
{
return [
'php_version' => PHP_VERSION,
'os' => PHP_OS,
'sapi' => PHP_SAPI,
'memory_limit' => ini_get('memory_limit'),
'max_execution_time' => ini_get('max_execution_time'),
'loaded_extensions' => get_loaded_extensions(),
];
}
}常见问题排查
| 问题 | 可能原因 | 解决方案 |
|---|---|---|
| 连接超时 | 网络问题/配置错误 | 检查配置,增加超时时间 |
| 权限不足 | 文件/目录权限 | 使用 chmod/chown 修正 |
| 性能下降 | 索引缺失/数据量大 | 添加索引,优化查询 |
| 数据不一致 | 并发冲突/事务残留 | 使用锁机制和事务 |
| 内存溢出 | 大数据集/未释放资源 | 增大内存限制,分批处理 |
故障排除步骤
- 检查错误日志和异常信息
- 确认配置和环境是否正确
- 使用调试工具逐步排查
- 参考官方文档查找已知问题
版本兼容性说明
| 功能 | 最低版本 | 说明 |
|---|---|---|
| 基础功能 | PHP 8.1 | 本文档基准版本 |
| 只读属性 | PHP 8.1 | public readonly 修饰符 |
| 枚举类型 | PHP 8.1 | enum 类型和 match 表达式 |
| Fiber | PHP 8.1 | 协程/轻量级并发 |
| 命名参数 | PHP 8.0 | foo(arg_name: value) |
| 联合类型 | PHP 8.0 | `int |
| Null 安全运算符 | PHP 8.0 | $obj?->method() |
| 析构器 promotion | PHP 8.0 | __construct(public $x) |
php
<?php
declare(strict_types=1);
// 版本兼容性检测
function ensureVersion(string $minVersion): void
{
if (version_compare(PHP_VERSION, $minVersion, '<')) {
throw new RuntimeException(
sprintf('需要 PHP %s+, 当前版本: %s', $minVersion, PHP_VERSION)
);
}
}
ensureVersion('8.1.0');