Marco Rios
Marco Rios

Reputation: 7

Return key that is NOT found in array with array_search php

I'm trying to get ONLY the keys of an array that is not found with array_search (false), but i cannot come with any ideas on that...

At the moment now i'm getting the found array with:

$ArrayA = ["Genre1" => 1, "Genre2" => 2, "Genre3" => 3, "Genre4" => 4];
$ArrayB = [1, 2, 3];

foreach ($ArrayB as $i) {
    $found = array_search($i, $ArrayA);

    if ($found === false) {
        echo "$i is not in the array";
        echo "list keys that are not in ArrayB";

    } else {
        echo "$i is in the array at <strong>$found</strong>";
    }
}               

But as how i say in the tittle, I need to print the key of the values that wasn't found in the search...

Any ideas how can I get those keys?... I know that search only return false if is not found, is there any other way to get those keys that wasn't found instead of the found key?

Thanks a lot!!!

Upvotes: 0

Views: 127

Answers (3)

Meher Ullah Khan Raj
Meher Ullah Khan Raj

Reputation: 449

Use array_intersect() instead:

$result = array_intersect($ArrayA, $ArrayB);

Upvotes: 0

laloune
laloune

Reputation: 673

what about array_diff ?

$ArrayA = ["Genre1" => 1, "Genre2" => 2, "Genre3" => 3, "Genre4" => 4];
$ArrayB = [1, 2, 3];

$valuesArrayA = array_values($ArrayA);

$notInArrayA = array_diff($valuesArrayA,$ArrayB);

Upvotes: 0

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

You can use array_diff

print_r(array_diff($ArrayA, $ArrayB));

If you want only the keys use array_keys(array_diff($ArrayA, $ArrayB))

Working example : https://3v4l.org/h7DRv

Upvotes: 2

Related Questions