开发者

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

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 eleme开发者_高级运维nts that I wish to remove from array A.

What is the most efficient way to achieve this?


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.


Use array_diff()


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜