简而言之: 如果你的数组大小相同且键值相同,则使用foreach()
可以获得最佳性能。如果你喜欢简洁的函数式代码并且只需要松散比较,则使用array_diff_assoc()
。如果你喜欢函数式代码并且需要严格比较,则使用array_filter()
。
这个答案将使用以下新的示例数据来澄清所需的行为:
$array1 = ['keepThis', 'remove', false, 'keep', 'save', 'delete'];
$array2 = ['hangOnto', 'remove', null, 'retain', 'keep', 'delete'];
由于数组中索引为[1]
的值相同,这些值不会被存储在清理后的数组(remove
)中。对于索引为[5]
(delete
)的元素也是如此。虽然keep
在两个数组中都存在,但元素没有共享相同的索引/键。
正确的结果应该是:
$clean1 = [0 => 'keepThis', 2 => false, 3 => 'keep', 4 => 'save'];
$clean2 = [0 => 'hangOnto', 2 => null, 3 => 'retain', 4 => 'keep'];
The asker's foreach()
loop enjoys the benefit of having the smallest time complexity because it only traverses the first array just one time. However, if the array might not have the same count or keyed elements, then that code risks generating Warnings at $array2[$key]
or not fully populating $clean2
.
array_diff_assoc()
offers a concise functional approach, but only implements loose comparisons (if it matters): (Demo)
var_export([
array_diff_assoc($array1, $array2),
array_diff_assoc($array2, $array1)
]);
Bad Result (because false
is loosely equal to null
):
[
[0 => 'keepThis', 3 => 'keep', 4 => 'save'],
[0 => 'hangOnto', 3 => 'retain', 4 => 'keep'],
]
You can try to overcome the PHP core algorithm for array_diff_uassoc()
, but this will either be unstable or prohibitively over-complicated.
array_filter()
is able to make strict comparisons and is not horribly verbose thanks to PHP7.4's arrow function syntax. (Demo)
var_export([
array_filter(
$array1,
fn($value, $index) => $array2[$index] !== $value,
ARRAY_FILTER_USE_BOTH
),
array_filter(
$array2,
fn($value, $index) => $array1[$index] !== $value,
ARRAY_FILTER_USE_BOTH
)
]);