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

Susan Sarandon
Release: 2024-10-27 05:51:03
Original
537 people have browsed it

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!