PHP 数组作为列表使用时应当遵循的规范

PHP 的数组可以作为列表使用,在使用时,应当遵循以下规范。

列表中的值的类型应当相同

$goodList = [
    'a',
    'b',
];

$badList = [
    'a',
    1,
];

忽略索引

// 好
foreach ($list as $element) {
}

// 不好:不需要暴露索引
foreach ($list as $index => $element) {
}

// 不好:不需要用到索引
for ($i = 0; $i < count($list); $i++) {
}

不要删除列表,应当使用过滤器来得到一个新的列表

// 不好
$list = [1, 2, 3];
unset($list[1]);

在使用过滤器时,不应当根据索引来筛选

// 好
array_filter(
    $list, 
    function (string $element): bool { 
        return strlen($element) > 2; 
    }
);

// 不好:使用了索引
array_filter(
    $list, 
    function (int $index): bool { 
        return $index > 3;
    },
    ARRAY_FILTER_USE_KEY
);

// 不好:同时使用了索引和值
array_filter(
    $list, 
    function (string $element, int $index): bool { 
        return $index > 3 || $element === 'Include';
    },
    ARRAY_FILTER_USE_BOTH
);
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 1

为什么使用了数组索引就没那么好呢?

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!