Home >Backend Development >PHP Tutorial >How to Extract Array Elements Based on a Specific Key Prefix in PHP?
Extracting Array Elements Based on Prefix Availability
In a scenario where you have an array with varying key prefixes, extracting only elements that start with a particular prefix can be a useful task. Let's consider an example array:
array( 'abc' => 0, 'foo-bcd' => 1, 'foo-def' => 1, 'foo-xyz' => 0, // ... )
Challenge: Retain only elements starting with 'foo-'.
Functional Approach:
<code class="php">$array = array_filter($array, function($key) { return strpos($key, 'foo-') === 0; }, ARRAY_FILTER_USE_KEY);</code>
The array_filter function with the anonymous function checks if the key of each element starts with 'foo-'. If this condition is met, the element is retained in the modified array.
Procedural Approach:
<code class="php">$only_foo = array(); foreach ($array as $key => $value) { if (strpos($key, 'foo-') === 0) { $only_foo[$key] = $value; } }</code>
This approach iterates over the array, checking each key for the 'foo-' prefix. If found, the element is added to a new array containing only those elements that meet the criterion.
Procedural Approach Using Objects:
<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>
With this approach, an ArrayIterator object is used to traverse the original array. Each key is inspected for the 'foo-' prefix, and corresponding elements are added to a new array.
The above is the detailed content of How to Extract Array Elements Based on a Specific Key Prefix in PHP?. For more information, please follow other related articles on the PHP Chinese website!