Keeping Only Array Elements with Specific Key Prefixes
Consider an array with keys prefixed with a specific string, such as "foo-". Removing all elements with keys not matching this prefix can be achieved using various approaches.
Functional Approach
<code class="php">$array = array_filter($array, function($key) { return strpos($key, 'foo-') === 0; }, ARRAY_FILTER_USE_KEY);</code>
Procedural Approach
<code class="php">$only_foo = array(); foreach ($array as $key => $value) { if (strpos($key, 'foo-') === 0) { $only_foo[$key] = $value; } }</code>
Object-Oriented Procedural Approach
<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>
These approaches allow you to retain only the elements from the original array that have keys beginning with the specified string.
The above is the detailed content of How to Extract Array Elements Based on Key Prefixes in PHP?. For more information, please follow other related articles on the PHP Chinese website!