Home  >  Article  >  Backend Development  >  How to Filter an Array Based on Key Prefix in PHP?

How to Filter an Array Based on Key Prefix in PHP?

DDD
DDDOriginal
2024-10-29 21:54:29886browse

How to Filter an Array Based on Key Prefix in PHP?

Filtering Array Elements Based on Key Prefix

Given an array with keys that follow a specific pattern, it may be necessary to selectively retain only the elements satisfying certain criteria. In this case, we aim to filter an array, retaining only elements whose keys begin with a particular string, such as "foo-".

Functional Approach

To achieve this using a functional approach, one option is to employ the array_filter() function in conjunction with a custom callback. The callback function examines each key and returns true if it starts with "foo-". The array_filter() function then filters the array based on this condition, preserving only the matching keys.

<code class="php">$array = array_filter($array, function($key) {
    return strpos($key, 'foo-') === 0;
}, ARRAY_FILTER_USE_KEY);</code>

Procedural Approach

A procedural approach involves manually iterating through the array. For each key, we check if it starts with "foo-", and if so, we add the key-value pair to a new array.

<code class="php">$only_foo = array();
foreach ($array as $key => $value) {
    if (strpos($key, 'foo-') === 0) {
        $only_foo[$key] = $value;
    }
}</code>

Procedural Approach Using Objects

Another procedural approach involves using an ArrayIterator to iterate over the array. This approach allows us to access both the key and value for each element. We manually filter the array by checking if each key starts with "foo-" and adding matching elements to a new 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 an Array Based on Key Prefix in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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