user5660692
user5660692

Reputation:

Find array key where value contains a specific value

I have an associative array where each value is a list of numbers, like this:

$a['i']=[111, 333];

Given the value 333, how can I find the key i. That is, the key for a list which contains 333.

Upvotes: 2

Views: 197

Answers (1)

Sean Bright
Sean Bright

Reputation: 120644

If the values in your primary array were simple types - numbers, strings, etc. - you would want to use array_search to find the associated key. In your case the value of each element is another array, so you have to explicitly loop over each element and search the resulting array for your value. Something like this should do the trick:

function get_key_from_value(array $arr, $needle)
{
    foreach ($arr as $key => $value)
        if (in_array($needle, $value, true))
            return $key;
    return null;
}

And you would call it like this:

echo get_key_from_value($a, 333);

Update: It has been mentioned in comments that this is not a general purpose solution, so I've implemented a version that is:

function array_search_recursive($needle, array $haystack, $strict = false)
{
    foreach ($haystack as $key => $value) {
        if (is_array($value)) {
            if (!is_null(array_search_recursive($needle, $value, $strict))) {
                return $key;
            }
        } else {
            if ($strict && $value === $needle) {
                return $key;
            } else if (!$strict && $value == $needle) {
                return $key;
            }
        }
    }
    return null;
}

Which can be called like this (the order of arguments is based on array_search):

echo array_search_recursive(333, $a);

Upvotes: 5

Related Questions