Nymur Rahman
Nymur Rahman

Reputation: 3

How to compare two arrays using a for loop and keep the unique from first array?

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>";
}

Upvotes: 0

Views: 181

Answers (3)

LF-DevJourney
LF-DevJourney

Reputation: 28529

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);

Upvotes: 0

Vector
Vector

Reputation: 3235

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
}

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

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]);
    }
}

Upvotes: 3

Related Questions