0

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.

Louis__
  • 49
  • 4

1 Answers1

0

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

Geoffrey
  • 5,407
  • 10
  • 43
  • 78
  • Thanks Geoffrey. I was hoping though for a solution without looping the array. – Louis__ Sep 27 '21 at 11:27
  • @Louis__ can you have 'foo-' keys in the outer array as well? – Geoffrey Sep 27 '21 at 11:35
  • No, they're part of the inner arrays only. – Louis__ Sep 27 '21 at 11:36
  • OK. What is the expected end result: (1) an array of strings starting with 'foo' or (2) an array with the same initial structure, except that for the inner arrays, elements with keys starting with 'foo' have been removed(or kept)? – Geoffrey Sep 27 '21 at 11:43
  • I'd like to remove the array items of the outer array if the inner array does not contain a key starting with 'foo-'...perhaps I should rewrite my code. – Louis__ Sep 27 '21 at 11:50
  • Please see my updated answer. – Geoffrey Sep 27 '21 at 12:15