Filter Array Elements Based on Key Prefix
You have an array containing elements with keys of varying prefixes, and you need to isolate only those with keys starting with a specific string, e.g., "foo-".
Functional Approach
To retain only the elements with keys beginning with "foo-" using a functional approach in PHP, utilize PHP's array_filter() function along with an anonymous function to inspect each key:
<code class="php">$array = array_filter($array, function($key) { return strpos($key, 'foo-') === 0; }, ARRAY_FILTER_USE_KEY);</code>
This function loops through the $array and returns a new array containing only those elements whose keys satisfy the condition of starting with "foo-".
Procedural Approach
For a procedural approach, you can use a foreach loop to iterate through the $array and manually select the desired elements:
<code class="php">$only_foo = array(); foreach ($array as $key => $value) { if (strpos($key, 'foo-') === 0) { $only_foo[$key] = $value; } }</code>
In this case, the $only_foo array is manually populated with the elements meeting the key prefix criterion.
Procedural Approach with Objects
Using OOP, you can employ the ArrayIterator class to iterate over the $array and filter the desired elements:
<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>
This time, the ArrayIterator provides the ability to process arrays using object-oriented constructs.
The above is the detailed content of How to Filter Array Elements Based on Key Prefix in PHP?. For more information, please follow other related articles on the PHP Chinese website!