I have an array that looks like this:
array(
\'abc\' => 0,
\'foo-bcd\' => 1,
\'foo-def\' => 1,
\'foo-xyz\' => 0,
// ...
)
From PHP5.6, the array keys can be the sole subject of the filtration by using the ARRAY_FILTER_USE_KEY constant/flag.
From PHP7.4, arrow functions make custom functions more concise and allow values to be passed into the custom function's scope without use().
From PHP8, str_starts_with() can take the place of strpos(...) === 0
Code: (Demo)
$array = [
'abc' => 0,
'foo-bcd' => 1,
'foo-def' => 1,
'foo-xyz' => 0,
];
$prefix = 'foo';
var_export(
array_filter(
$array,
fn($key) => str_starts_with($key, $prefix),
ARRAY_FILTER_USE_KEY
)
);
Output:
array (
'foo-bcd' => 1,
'foo-def' => 1,
'foo-xyz' => 0,
)