1

I was wondering about this kind of situation.

What if i have a huge array say about 50k items or more.

Now let's say many of that array keys have prefix let's name it settings_, now if i want to select all values where key begins by settings_ would i need to loop trough all 50k items or is there a better way?

And say there is some "magical" way to do this with single level arrays, what about multidimensional ones?

Linas
  • 4,380
  • 17
  • 69
  • 117
  • I think the only way is to go through the `50k` array keys, match them with a regex, then get the array values of the matching keys. – Aziz Dec 05 '12 at 17:18
  • A similar question: http://stackoverflow.com/questions/4979238/php-get-all-keys-from-a-array-that-start-with-a-certain-string – Aziz Dec 05 '12 at 17:19
  • Another similar question: http://stackoverflow.com/questions/11051707/excluding-array-keys-that-start-with-from-foreach-in-php – Aziz Dec 05 '12 at 17:20
  • Aziz links point to the answer you are looking for, but keep in mind this might mean you are better off having all those values under a ['settings'] key. – andreshernandez Dec 05 '12 at 17:36

2 Answers2

3

There is preg_grep, which matches array values. Since you want to search keys, you need to invert keys and values with array_flip:

<?php
$array = array(
    'armenia' => 0,
    'argentina' => 1,
    'brazil' => 2,
    'bolivia' => 3,
    'congo' => 4,
    'denmark' => 5
);
$filtered = array_flip(preg_grep('/^b/', array_flip($array)));

var_dump($filtered);
/*
Output:

array(2) {
  ["brazil"]=>
  int(2)
  ["bolivia"]=>
  int(3)
}
*/
lortabac
  • 589
  • 4
  • 16
  • I wonder how it perform vs looping trough all arrays and picking what you need – Linas Dec 05 '12 at 17:33
  • @Linas I did a quick test and preg_grep + array_flip performed much better than looping. But I have no idea how it would perform with a big array. – lortabac Dec 05 '12 at 17:44
0
$arr_main_array = array('something_test' => 123, 'other_test' => 456, 'something_result' => 789);

foreach($arr_main_array as $key => $value){
    $exp_key = explode('_', $key);
    if($exp_key[0] == 'something'){
        $arr_result[] = $value;
    }
}

if(isset($arr_result)){
   print_r($arr_result);
}

You can execute the code at http://sandbox.onlinephpfunctions.com/code/884816dd115b3ccc610e1732e9716471a7b29b0f

Developer-Sid
  • 1,372
  • 11
  • 9