phparraysfilterarray-differencearray-intersect

Get array differences and intersections by comparing two flat arrays without using array functions


I want to find array difference without using any array functions like array_diff() or in_array().

This is my code

$a = array('a','b','c','d','k');
$b = array('g','h','i','b','a','d','c');
$match = array();
$miss_match = array();

$count_a = count($a);
$count_b = count($b);

for ($i = 0; $i < $count_a; $i++)
    {
        for ($j = 0; $j < $count_b; $j++)
            {
            if ($a[$i] == $b[$j])
                {
                $match[] = $a[$i];
                break;
                }
            else
                {
                $miss_match[] = $b[$j];
                }   
            }
    }
print_r($match) . '<br />';
print_r($miss_match);

And I am getting this result

Array ( [0] => a [1] => b [2] => c [3] => d )

Array ( [0] => g [1] => h [2] => i [3] => b [4] => g [5] => h 
[6] => i [7] => g [8] => h [9] => i [10] => b [11] => a [12] => d 
[13] => g [14] => h [15] => i [16] => b [17] => a [18] => g 
[19] => h [20] => i [21] => b [22] => a [23] => d [24] => c ) 

My expected result is

Array ( [0] => g [1] => h [2] => i [3] => k )

Solution

  • You're adding the element to the miss_match array for every element of the other array that it doesn't match. But if it doesn't match this element, it might still match a later element.

    You have to go through the entire array before determining that it doesn't match any of them.

    for($i=0; $i<$count_a;$i++)
    {
        for($j=0; $j<$count_b;$j++)
        {
            $matched = false;
            if($a[$i]==$b[$j])
            {
                $match[] = $a[$i];
                $matched = true;
                break;
            }
        }
        if (!$matched)
        {
            $miss_match[] = $a[$i];
        }   
    }
    

    Result:

    Array
    (
        [0] => a
        [1] => b
        [2] => c
        [3] => d
    )
    Array
    (
        [0] => k
    )