How to Extract Array Elements Based on a Specific Key Prefix in PHP?

DDD
Release: 2024-10-28 18:08:02
Original
716 people have browsed it

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,
  // ...
)
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!