0

I am trying to search an array of arrays and if the needle is found I want to return or at least know the keys for the match.

For example given:

['foo'] => 
     ['bar'] => 'blah'

Searching for 'blah' I need to know there is a match and the keys are 'foo' and 'bar'

I have managed to implement a search which returns boolean for a match:

function search_array($needle, $haystack) {
        if(in_array($needle, $haystack)) {
            return true;
        }
        foreach($haystack as $element) {
            var_dump($element);
            if(is_array($element) && $this->search_array($needle, $element))
               return true;
        }
        return false;
}

But I am struggling with how to know the keys. Is this even possible?

0

2 Answers 2

3

Yes it is possible. One solution is to:

  • In the base case utilize array_search() to get the key.
  • In the recursive case, when iterating over each element in the haystack (before recursing) use the $key => $value syntax of foreach. Then when the recursive call yields a value, check if the returned value is an array (by using is_array()) - if so, use array_unshift() to push the current key onto the returned array. Otherwise return an array with the key and the returned value.

    function search_array($needle, $haystack) {
        if(in_array($needle, $haystack)) {
            return array_search($needle, $haystack);
        }
        foreach($haystack as $key => $element) {
            if(is_array($element) && search_array($needle, $element)) {
                $searchReturn = search_array($needle, $element);
                if (is_array($searchReturn)) {
                    array_unshift($searchReturn, $key);
                    return $searchReturn;
                }
                return [$key, $searchReturn];
            }
        }
        return false;
    }
    

See it demonstrated in this playground example.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that worked albeit I had to modify the return at line 3 to in_array in my case.
1

You can do it like this, since it's 2-dimensional array.

function search_array($needle, $haystack) {
    foreach($haystack as $key => $value) {
        if ($value == $needle) {
            return array($key);
        } else if (is_array($value)) {
            foreach ($value as $k => $v) {
                if ($v == $needle) {
                    return array($key, $k);
                }
            }
        }
    }
}

For an n-dimensional array you should use a recursive function...

1 Comment

This is an interesting non-recursive solution, thnaks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.