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

How to Filter Array Elements by Key Prefix in PHP?

Barbara Streisand
Release: 2024-10-27 12:30:30
Original
559 people have browsed it

How to Filter Array Elements by Key Prefix in PHP?

Filter Array Elements by Key Prefix

Given an array with keys and values, how can one remove all elements whose keys do not start with a specific string? For instance, given the following array:

<code class="php">array(
  'abc' => 0,
  'foo-bcd' => 1,
  'foo-def' => 1,
  'foo-xyz' => 0,
  // ...
)</code>
Copy after login

The goal is to retain only the elements with keys starting with "foo-".

Functional Approach:

Using the array_filter function, you can filter the array and retain only the desired elements:

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

Procedural Approach:

Alternatively, a procedural approach can be used:

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

Procedural Approach with Objects:

Using an iterator, one can also filter the 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>
Copy after login

The above is the detailed content of How to Filter Array Elements by 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