Search code examples
phparrayskeyfilteringarray-difference

Remove associative elements from a flat array where the key does not exist as a value into another flat array


I have two arrays named rows and contacts.

The first array rows is like:

Array
(
    [0] => [email protected]
    [1] => [email protected]
    [2] => [email protected]
    [3] => [email protected]
)

The second array contacts is as:

Array
(
    [[email protected]] => [email protected]
    [[email protected]] => Ram
    [[email protected]] => Vinay
    [[email protected]] => Manoj
    [[email protected]] => Homan
)

What I want is the contacts array to be as :

Array
    (
        [[email protected]] => Ram
        [[email protected]] => Manoj
        [[email protected]] => Homan
    )

Edit

I tried some functions like array_diff(), array_keys() etc. but they are not giving me the desired output, may be I am not able to use them correctly....!

I don't want to use loop for this purpose because the given arrays are only sample data but in real they are very huge.


Solution

  • Another way:

    $contacts = array_diff_key($contacts, array_flip($rows));