Skip to content
Advertisement

PHP – Get multidimensional array value based on the value of another parameter

Imagine I have this array:

Array
(
    [0] => Array
        (
            [email] => a@a.com
            [name] => a
        )

    [1] => Array
        (
            [email] => b@b.com
            [name] => b
        )
)

I use this code to check if my email exists in this multi array:

in_array($user->user_email, array_column($array, 'email'))

Now, my question is: How can I get the value of the parameter ‘name’, where the email is matching my variable. So if my $user->user_email is equal to ‘a@a.com’ i need the name value, which is ‘a’. Is it possible in php?

Advertisement

Answer

Try this:

$index = array_search($user->user_email, array_column($array, 'email'));
if ($index !== false) $name = $array[$index]['name'];

This relies on the fact that the runtime array created by array_column preserves, I believe, the order in which the items were extracted. Ergo, an index read from this array can be used to reference the original array.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement