PHP - get all keys from a array that start with a certain string
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();
}
This is how I would do it, though I can't give you a more efficient advice before understanding what you want to do with the values you get.
$search = "foo-";
$search_length = strlen($search);
foreach ($array as $key => $value) {
if (substr($key, 0, $search_length) == $search) {
...use the $value...
}
}
Simply I used array_filter
function to achieve the solution as like follows
<?php
$input = array(
'abc' => 0,
'foo-bcd' => 1,
'foo-def' => 1,
'foo-xyz' => 0,
);
$filtered = array_filter($input, function ($key) {
return strpos($key, 'foo-') === 0;
}, ARRAY_FILTER_USE_KEY);
print_r($filtered);
Output
Array
(
[foo-bcd] => 1
[foo-def] => 1
[foo-xyz] => 0
)
For live check https://3v4l.org/lJCse