lcdservices
lcdservices

Reputation: 863

How to find key where value is array with certain key using php?

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.

Upvotes: 1

Views: 88

Answers (2)

LF-DevJourney
LF-DevJourney

Reputation: 28529

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));

Upvotes: 1

Mohammad
Mohammad

Reputation: 21489

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

Upvotes: 0

Related Questions