Ali Zia
Ali Zia

Reputation: 3875

I want to get the elements that are not present in array 1 but present in array 2

I have 2 arrays.

$first = [
    '01/10/2019' =>
        [
            21498226,
            21497647,
            21497649,
            21497635,
            21497636,
            21497637,
            21497728,
            21497822,
            21498028,
            21497638,
        ],
];

$second = [
    '01/10/2019' =>
        [
            21498226,
            21497647,
            12345678,
            87654321,
            21497636,
            21497637,
            21497728,
            21497822,
            21498028,
            21497638,
        ],
];

I have written this code

$notPresent = [];
foreach ($second as $date => $code) {
    foreach ($code as $c) {
        if (array_key_exists($date, $first)) {
            if (!in_array($c, $first[$date])) {
                $notPresent[$date] = $code;
            }
        } else {
            $notPresent[$date] = $code;
        }
    }
}

But it is returning me all 10 values. What I really want is to have only those values that are not present in $first. Like 12345678 and 87654321.

Upvotes: 1

Views: 59

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Swap the arrays around so that you are looking for elements of array 2 that are not in array 1, and that's word-for-word what array_diff does.

returns the values in array1 that are not present in any of the other arrays

You will need to iterate over the "parent" arrays, naturally, so array_map can help too. (Although, to preserve the keys, you'll need some fiddling around with array_keys and array_combine since array_map doesn't preserve keys...)

$notPresent = array_combine(
    array_keys($second),
    array_map('array_diff', $second, $first)
);

EDIT I just realised that the above code assumes that the keys exist in both arrays in the same order. Since that's almost certainly not the case, here's an adjusted version that handles that.

$notPresent = array_combine(
    array_keys($second),
    array_map(function($key,$values) use ($first) {
        if( array_key_exists($key,$first)) {
            return array_diff($values, $first[$key]);
        }
        return $values;
    }, array_keys($second), array_values($second))
);

Upvotes: 3

Related Questions