How to get all keys from a array that start with a certain string?

Alex picture Alex · Feb 12, 2011 · Viewed 83.1k times · Source

I have an array that looks like this:

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

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

Answer

erisco picture erisco · Feb 12, 2011

Functional approach:

$array = array_filter($array, function($key) {
    return strpos($key, 'foo-') === 0;
}, ARRAY_FILTER_USE_KEY);

Procedural approach:

$only_foo = array();
foreach ($array as $key => $value) {
    if (strpos($key, 'foo-') === 0) {
        $only_foo[$key] = $value;
    }
}

Procedural approach using objects:

$i = new ArrayIterator($array);
$only_foo = array();
while ($i->valid()) {
    if (strpos($i->key(), 'foo-') === 0) {
        $only_foo[$i->key()] = $i->current();
    }
    $i->next();
}