Home  >  Article  >  Backend Development  >  How to Extract Array Elements Based on Key Prefixes in PHP?

How to Extract Array Elements Based on Key Prefixes in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 05:51:03539browse

How to Extract Array Elements Based on Key Prefixes in PHP?

Keeping Only Array Elements with Specific Key Prefixes

Consider an array with keys prefixed with a specific string, such as "foo-". Removing all elements with keys not matching this prefix can be achieved using various approaches.

Functional Approach

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

Procedural Approach

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

Object-Oriented Procedural Approach

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

These approaches allow you to retain only the elements from the original array that have keys beginning with the specified string.

The above is the detailed content of How to Extract Array Elements Based on Key Prefixes 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