"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Extract Array Elements Based on a Specific Key Prefix in PHP?

How to Extract Array Elements Based on a Specific Key Prefix in PHP?

Published on 2024-11-22
Browse:457

How to Extract Array Elements Based on a Specific Key Prefix in PHP?

Extracting Array Elements Based on Prefix Availability

In a scenario where you have an array with varying key prefixes, extracting only elements that start with a particular prefix can be a useful task. Let's consider an example array:

array(
  'abc' => 0,
  'foo-bcd' => 1,
  'foo-def' => 1,
  'foo-xyz' => 0,
  // ...
)

Challenge: Retain only elements starting with 'foo-'.

Functional Approach:

$array = array_filter($array, function($key) {
    return strpos($key, 'foo-') === 0;
}, ARRAY_FILTER_USE_KEY);

The array_filter function with the anonymous function checks if the key of each element starts with 'foo-'. If this condition is met, the element is retained in the modified array.

Procedural Approach:

$only_foo = array();
foreach ($array as $key => $value) {
    if (strpos($key, 'foo-') === 0) {
        $only_foo[$key] = $value;
    }
}

This approach iterates over the array, checking each key for the 'foo-' prefix. If found, the element is added to a new array containing only those elements that meet the criterion.

Procedural Approach Using Objects:

$i = new ArrayIterator($array);
$only_foo = array();
while ($i->valid()) {
    if (strpos($i->key(), 'foo-') === 0) {
        $only_foo[$i->key()] = $i->current();
    }
    $i->next();
}

With this approach, an ArrayIterator object is used to traverse the original array. Each key is inspected for the 'foo-' prefix, and corresponding elements are added to a new array.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3