Home > Backend Development > PHP Tutorial > How to Filter Array Elements Based on Key Prefix in PHP?

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

Linda Hamilton
Release: 2024-10-28 11:42:02
Original
858 people have browsed it

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

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template