Skip to content
Advertisement

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

Advertisement

Answer

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]);
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement