1
$a = ["a","b","c","a","b"];
$b = ["a","c"];
array_diff($a,$b);
//output will be [b,b]

but that is not a proper difference it can also be

//output [b,a,b]  <- this is what I am trying to achieve

I tried foreach loop and for loop but failed to get it...

Foreach example I tried

$a = ["a","b","c","a","b"];
$b = ["a","c"];
echo array_diff_custom($a,$b),"<br>";

function array_diff_custom($a,$b){
$result =0;
    foreach($a as $key=>$val){
        foreach($b as $key2=>$val2){
                  if($val == $val2){
                     unset($a[$key]);
                   }         

        }

    }
$result = count($a);
return $result;
}


echo array_diff_custom($b,$a);

for loop example, I tried

$a = ["a","b","c","a","b"];
$b = ["a","c"];
echo array_diff_custom($a,$b),"<br>";

function array_diff_custom($a,$b){
$result =0;
    for($i=0;$i<count($a);$i++){
        for($j=0;$j<count($b);$j++){
                 //echo $a[$i]."-".$b[$j]."<br>";
                  if($a[$i] == $b[$j]){
                     unset($a[$i]);
                   }         

        }

    }
$result = count($a);
return $result;
}


echo array_diff_custom($b,$a);

I am using count($resut) in example function I created but you can just simply return $a and can print_R(array_Diff_custom) to check the output...

Sayed Mohd Ali
  • 2,156
  • 3
  • 12
  • 28

1 Answers1

3

You can just unset items, presented in the 2nd array, from the first one only once

function array_diff_custom($a,$b){
  foreach($b as $x){
    if($k = array_keys($a, $x)) {
        unset($a[$k[0]]);
    }
  }
  return $a;
}

print_r(array_diff_custom($a,$b)); 

demo

splash58
  • 26,043
  • 3
  • 22
  • 34
  • Note that it will provide empty result if `count($b) > count($a)`, you might need to swap the arrays, if this is not the expected result – Cid Aug 23 '19 at 11:50
  • @Cid empty is fine... if all the values are getting subtracted that is the logic... – Sayed Mohd Ali Aug 23 '19 at 11:54