Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 elements that I wish to remove from array A.

What is the most efficient way to achieve this?

like image 851
sterling Avatar asked Nov 29 '10 20:11

sterling


People also ask

How do you remove all elements from one array from another array?

For removing one array from another array in java we will use the removeAll() method. This will remove all the elements of the array1 from array2 if we call removeAll() function from array2 and array1 as a parameter.

Which method is used to remove an element from the array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do I remove multiple elements from an array?

Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.

How do you remove an array from an array?

You can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically.


1 Answers

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.

like image 179
user187291 Avatar answered Oct 31 '22 16:10

user187291