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?
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.
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.
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.
You can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With