Search code examples
phparrayskeyfilteringarray-filter

Remove all elements from array that have a key that does not start with a certain string


I have an array that looks like this:

array(
  'abc' => 0,
  'foo-bcd' => 1,
  'foo-def' => 1,
  'foo-xyz' => 0,
  // ...
)

How can I retain only the elements that start with foo-?


Solution

  • Modification to erisco's Functional approach,

    array_filter($signatureData[0]["foo-"], function($k) {
        return strpos($k, 'foo-abc') === 0;
    }, ARRAY_FILTER_USE_KEY);
    

    this worked for me.