Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Get multidimensional array value based on the value of another parameter [duplicate]

Imagine I have this array:

Array
(
    [0] => Array
        (
            [email] => [email protected]
            [name] => a
        )

    [1] => Array
        (
            [email] => [email protected]
            [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 '[email protected]' i need the name value, which is 'a'. Is it possible in php?

like image 637
jens_vdp Avatar asked Sep 18 '26 19:09

jens_vdp


1 Answers

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.

like image 79
Mitya Avatar answered Sep 21 '26 09:09

Mitya