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-
?
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();
}