1

For simple arrays with key value pairs, we can easily locate the key based on the value using array_search(). But I have an array in which the values may be a string or an array, and need to find the key where the value is an array with specific keys.

$myArray = array(
  0 => string_value,
  1 => string_value2,
  3 => array(
         'config' => array(
           'option1' => value1,
           'option2' => value2,
         ),
       ),
  4 => string_value3,
);

I need to find the key for the element where the child array has a key config -- i.e. I should search for config and return 3.

I'd prefer not to cycle through the array. Not a big deal if that's the only option. But I'm wondering if there's a more elegant way to locate that key.

3
  • There's no other way except checking every item. Commented Jan 7, 2017 at 14:26
  • And you have tried WHAT? Commented Jan 7, 2017 at 14:26
  • If you already have a way of doing this (like iterating through all elements) and just wonder if there are a better way, I would recommend posting your working solution on Code Review instead. Commented Jan 7, 2017 at 14:48

2 Answers 2

1

use array_filter to filter the array with config.

$o = array_filter($array, function($v){return !empty($v['config']) ? true : false;});
var_dump(array_keys($o));
Sign up to request clarification or add additional context in comments.

1 Comment

This was definitely the most elegant solution.
0

You should iterate items of array and check value of every item in loop. Check if $item["config"] setted in loop, return index of loop item.

$index;
foreach ($myArray as $key => $item){
    if (isset($item["config"]))
        $index = $key;
}
echo $index;

See result of code in demo

3 Comments

And add a break
@MagnusEriksson If $item['config'] allway is array, you can use is_array() but in question both of them work.
You are correct. I misread the question. He wants $item to be an array, not necessarily $item['config'].

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.