Alex Alex - 5 months ago 20
PHP Question

PHP - get all keys from a array that start with a certain string

I have a array that looks like this:

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


How can I get only the elements that start with
foo-
?

Answer
$arr_main_array = array('foo-test' => 123, 'other-test' => 456, 'foo-result' => 789);

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

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