Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two arrays and remove matching elements from one for the next loop?

Tags:

arrays

php

How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A?

$A = array(1,2,3,4,5,6,7,8);
$B = array(1,2,3,4);

$C = array_intersect($A,$B);  //equals (1,2,3,4)
$A = array_diff($A,$B);       //equals (5,6,7,8)

Is this the simplest way or is there a way to use another function that I haven't thought of? My goal is to have an array that I can loop over, pulling out groups of related content (I have defined those relationships elsewhere) until the array returns false.

like image 340
kevtrout Avatar asked Oct 22 '08 11:10

kevtrout


People also ask

How do you compare two arrays with each other?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

How can I find not matching values in two arrays?

JavaScript finding non-matching values in two arrays The code will look like this. const array1 = [1, 2, 3, 4, 5, 6]; const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const output = array2. filter(function (obj) { return array1. indexOf(obj) === -1; }); console.

How do you find the matching element in two arrays?

Approach: Get the two java Arrays. Iterate through each and every element of the arrays one by one and check whether they are common in both. Add each common element in the set for unique entries.


1 Answers

You've got it. Just use array_diff or array_intersect. Doesn't get much easier than that.

Edit: For example:

$arr_1 = array_diff($arr_1, $arr_2);
$arr_2 = array_diff($arr_2, $arr_1);

Source

like image 61
rg88 Avatar answered Oct 07 '22 15:10

rg88