1

I have array:

$persons = [
   'name_1' => 'asfddf',
   'name_2' => 'gsdg',
   'name_3' => '23423',
   'name_aaa' => '123sdg',
   'test' => '123sdg',
   'other' => '123sdg',
   'name_5' => 'sdg2334',
];

How to get values from this array which in key have name ?

In my example I would like receive:

$persons = [
   'name_1' => 'asfddf',
   'name_2' => 'gsdg',
   'name_3' => '23423',
   'name_aaa' => '123sdg',
   'name_5' => 'sdg2334',
];

I can use foreach and check key by strpos, but maybe is better way for this? Any map reduce?

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
irepo
  • 23
  • 3
  • `foreach` is the simplest and the most readable way. Why are you trying to complicate things? – u_mulder Aug 03 '17 at 06:51
  • you could use [array_filter](http://php.net/manual/en/function.array-filter.php) with `ARRAY_FILTER_USE_KEY` and a callback if you want, but in the end it is the same as iterating the array with a `foreach`. – xander Aug 03 '17 at 06:52
  • @xander but note that `array_filter` uses __keys__ in callback since php5.6, so it won't work with older versions. – u_mulder Aug 03 '17 at 06:53

2 Answers2

3

Solution for PHP 5.6 & above:

You can use array_filter with ARRAY_FILTER_USE_KEY flag:

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

print_r($array);

Solution for older versions:

This uses key for comparison and then applies key intersection using array_intersect_key

$array = array_filter(array_keys($persons), function($key) {
    return strpos($key, 'name') === 0;
});

print_r(array_intersect_key($persons, array_flip($array)));

Prints:

Array
(
    [name_1] => asfddf
    [name_2] => gsdg
    [name_3] => 23423
    [name_aaa] => 123sdg
    [name_5] => sdg2334
)
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
0

well you can try this with substr

foreach($persons as $key => $value){
    if("name_" == substr($key,0,5)){
    // process the value
     }
 }

Or you can simply do this using preg_match

foreach($persons as $key => $value){
    if (preg_match('/name_/',$key)) {
        echo $value;
    }
}
Regolith
  • 2,944
  • 9
  • 33
  • 50