0

how to compare two array value and remove the duplicate value from the first array using php for example

$a = ['a','b','c','d','e','f'];
$b = ['a','e'];

$result_array = ['b','c','d','f'];

I tried this:

$a = ['a','b','c','d','e','f'];
$b = ['a','e'];

foreach($a as $key_a=>$val_a){
  $val = '';
  foreach($b as $key_b=>$val_b){
      if($val_a != $val_b){
        $val = $val_a;    
            }else{$val = $val_b;}

  }
  echo $val."<br>";
}

3 Answers3

3

This is probably a duplicate, but I'm bored. Just compute the difference:

$a = array_diff($a, $b);

Or loop the main array, check for each value in the other and if found unset from the main array:

foreach($a as $k => $v) {
    if(in_array($v, $b)) {
        unset($a[$k]);
    }
}

Or loop the other array, search for each value in the main array and use the key found to unset it:

foreach($b as $v) {
    if(($k = array_search($v, $a)) !== false) {
        unset($a[$k]);
    }
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • 1
    *"This is probably a duplicate, but I'm bored"* I know exactly how that feels :-). Plus it often takes longer to find the dupe than post the answer... – Nick Nov 20 '19 at 21:56
0

Have a look at this SO post look at the Edit3
Edit2 We used this code to compare two ArrayList and remove the duplicates from one as we only wanted the misspelled words
Example of code capture is a ArrayList

    for(int P = 0; P < capture.size();P++){

    String gotIT = capture.get(P);     
    String[] EMPTY_STRING_ARRAY = new String[0];
    List<String> list = new ArrayList<>();
    Collections.addAll(list, strArray);
    list.removeAll(Arrays.asList(gotIT));
    strArray = list.toArray(EMPTY_STRING_ARRAY); 
    // Code above removes the correct spelled words from ArrayList capture
    // Leaving the misspelled words in strArray then below they are added 
    // to the cboMisspelledWord which then holds all the misspelled words
}
Vector
  • 3,066
  • 5
  • 27
  • 54
0

You can make $b a dictionary, which will has better performance when the two array has many elements. Check the Demo

$a = ['a','b','c','d','e','f'];
$b = ['a','e'];
$dic = array_flip($b);
$result = array_filter($a, function($v)use($dic){return !isset($dic[$v]);});
print_r($result);

LF00
  • 27,015
  • 29
  • 156
  • 295