Home > database >  How to get array keys starting with string in multidimensional array?
How to get array keys starting with string in multidimensional array?

Time:09-27

I know how to get all array keys starting with a particular string in a single array >> How to get all keys from a array that start with a certain string?

But what would be the way to go for multidimensional arrays? For instance, how to find all keys starting with 'foo-' in:

$arr = array('first-key' => 'first value'.
             'sceond-key' => 'second value',
             array('foo-1' => 'val',
                   'bar'=> 'value',
                   'foo-2' => 'val2')
             );

Many thanks, Louis.

CodePudding user response:

You can still apply the solution from the linked question, but with an additional outer filter.

$outputArray = array_filter(
    $inputArray, 
    function ($element) {
        return ! is_array($element)
            || ! empty(
                   array_filter($element, function($key) {
                       return strpos($key, 'foo-') === 0;
                   }, ARRAY_FILTER_USE_KEY)
               );
    }
);

See https://3v4l.org/NsgpR for working code.

PHP Manual: is_array()

  • Related