Home >Backend Development >PHP Tutorial >How to Filter Array Elements by Key Prefix in PHP?
Filter Array Elements by Key Prefix
Given an array with keys and values, how can one remove all elements whose keys do not start with a specific string? For instance, given the following array:
<code class="php">array( 'abc' => 0, 'foo-bcd' => 1, 'foo-def' => 1, 'foo-xyz' => 0, // ... )</code>
The goal is to retain only the elements with keys starting with "foo-".
Functional Approach:
Using the array_filter function, you can filter the array and retain only the desired elements:
<code class="php">$array = array_filter($array, function($key) { return strpos($key, 'foo-') === 0; }, ARRAY_FILTER_USE_KEY);</code>
Procedural Approach:
Alternatively, a procedural approach can be used:
<code class="php">$only_foo = array(); foreach ($array as $key => $value) { if (strpos($key, 'foo-') === 0) { $only_foo[$key] = $value; } }</code>
Procedural Approach with Objects:
Using an iterator, one can also filter the array:
<code class="php">$i = new ArrayIterator($array); $only_foo = array(); while ($i->valid()) { if (strpos($i->key(), 'foo-') === 0) { $only_foo[$i->key()] = $i->current(); } $i->next(); }</code>
The above is the detailed content of How to Filter Array Elements by Key Prefix in PHP?. For more information, please follow other related articles on the PHP Chinese website!