What is the most efficient way to remove all the elements of one array from another array?

懵懂的女人 提交于 2020-01-11 04:58:04

问题


I have two arrays, array A contains a long list with some elements I want to remove. Array B is the full list of those elements that I wish to remove from array A.

What is the most efficient way to achieve this?


回答1:


array_diff is the obvious answer, but since you've asked for the most efficient way, here's a test

$big = range(1, 90000);
$remove = range(500, 600);

$ts = microtime(true);
$result = array_diff($big, $remove);
printf("%.2f\n", microtime(true) - $ts);

$ts = microtime(true);
$map = array_flip($remove);
$result = array();
foreach($big as $e)
    if(!isset($map[$e]))
        $result[] = $e;
printf("%.2f\n", microtime(true) - $ts);

prints on my machine

0.67
0.03

So the simple loop with a hash-based lookup is approximately 20 times faster than array_diff.




回答2:


Use array_diff()




回答3:


In the manual it gives for array_dif() this exaple:

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Outputs:

Array
(
    [1] => blue
)

Returns an array containing all the entries from array1 that are not present in any of the other arrays.



来源:https://stackoverflow.com/questions/4307863/what-is-the-most-efficient-way-to-remove-all-the-elements-of-one-array-from-anot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!