2

I have a multidimensional associative array. The top level keys are numbers and the associative arrays inside have strings for both keys and values.

Here is an example of the array dump:

Array
(
    [1] => Array
        (
            [AC21T12-M01] => 54318
        )

    [2] => Array
        (
            [AC03T11-F01] => 54480
        )

)

So I want to search for 'AC03T11-F01' and return 2 as the key position.

I tried array_search('AC03T11-F01', $array); but it didn't return anything so I'm guessing it's not a straightforward as I thought.

I've used the function below to key the key position when searching for a value, so maybe that could be adapted to search for keys too?

function getParentStack($child, $stack) {
    foreach ($stack as $k => $v) {
        if (is_array($v)) {
            // If the current element of the array is an array, recurse it and capture the return
            $return = getParentStack($child, $v);

            // If the return is an array, stack it and return it
            if (is_array($return)) {
                //return array($k => $return);
                return $k;
            }
        } else {
            // Since we are not on an array, compare directly
            if ($v == $child) {
                // And if we match, stack it and return it
                return array($k => $child);
            }
        }
    }

    // Return false since there was nothing found
    return false;
}
0

2 Answers 2

3
$search = 'AC03T11-F01';
$found =  false;

foreach($array as $key => $value) {
    if(isset($value[$search])) {
        $found = $key;
        break;
    }
}

Now check $found.

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

1 Comment

Thanks @AbraCadaver. That worked perfectly and only a few lines. Perfect :)
1

You might filter your array and then request keys:

$filtered = array_filter($array, function(item) {
  return item === 'AC03T11-F01'
});

var_dump( array_keys( $filtered ) );
//⇒ [ 2 ]

Whether you want to retrieve the key of the first occurence:

$keys = array_keys( array_filter($array, function(item) {
  return item === 'AC03T11-F01'
}));
echo ($key = count( $keys ) > 0 ? $keys[0] : null);
//⇒ 2

3 Comments

This does not return a single key as OP requested
@Kleskowy Updated an answer.
Thanks @mudasobwa. I've accepted AbraCadaver's answer, but I appreciate yours too :)

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.