0

I have two array as I mention below:

$arr1 = array("1","3","4","6");
$arr2 = array("2","3","4","5","7");

I want to get those elements that are not in $arr2 without using built-in function. So, how can I do this?

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
darkshadow
  • 37
  • 5

3 Answers3

1

You can loop twice and unset if matches and break the inner loop

$arr1 = array("1","3","4","6");
$arr2 = array("2","3","4","5","7");

foreach($arr1 as $k => $v){
    foreach($arr2 as $k1 => $v1){
        if($v == $v1){
            unset($arr1[$k]);break;
        }
    }
}
print_r($arr1);

Demo.

Output:

Array
(
    [0] => 1
    [3] => 6
)
Rahul
  • 18,271
  • 7
  • 41
  • 60
1

I was intrigued by the question of not using any of the array functions or specialty functions in PHP, so here is what I came up with to diff the two arrays (as they are written, no further testing has been performed, it would likely break) without using those functions. It requires some juggling:

$arr1 = array("1","3","4","6");
$arr2 = array("2","3","4","5","7");

$inTwo = array();
$notInTwo = array();

// get the matching elements from the two arrays to create a new array
foreach($arr1 AS $key => $val) {
    foreach($arr2 AS $key2 => $val2) {
        if($val == $val2) {
            $inTwo[] = $val2;
        }
    }
}

print_r($inTwo);
$match = NULL; // variable used to hold match values, so they can be skipped

foreach($arr1 AS $key3 => $val3) {
    foreach($inTwo AS $key4 => $val4) {
        echo $val3 . ' ' . $val4 . "\n";
        if(($val3 == $val4) || ($match == $val4)) { // test
            echo "match\n";
            $match = $val3; // set the new variable, to be checked on the next iteration
            echo $match ."\n";
            break;
        } else {
            $notInTwo[] = $val3;
            break;
        }
    }
}

print_r($notInTwo);

Here is the output (all test output left in for reference):

Array //print_r($inTwo);
(
    [0] => 3
    [1] => 4
)
1 3
3 3
match // set the match variable
3
4 3 // skip this due to the match
match // set the match variable
4
6 3
Array print_r($notInTwo);
(
    [0] => 1
    [1] => 6
)

EXAMPLE

Diffing two arrays requires some recursion. If you want to know how this works under the hood you could look into the source for PHP (and other languages that offer a diffing algorithm) to get an idea of how to do this. What I've written here is crude, a bull-in-the-China-shop approach to the problem.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
0

you can use array_walk with in_array

$r = [];
array_walk($arr1, function($v, $k) use (&$r, $arr2){
  !in_array($v,$arr2) ? ($r[]=$v) : '';
});
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20