Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting an element in an Associative Array in a different way in PHP

Ok I have this kind of associative array in PHP

$arr = array(
    "fruit_aac" => "apple",
    "fruit_2de" => "banana",
    "fruit_ade" => "grapes",
    "other_add" => "sugar",
    "other_nut" => "coconut",
);

now what I want is to select only the elements that starts with key fruit_. How can be this possible? can I use a regex? or any PHP array functions available? Is there any workaround? Please give some examples for your solutions

like image 624
Netorica Avatar asked Dec 13 '22 01:12

Netorica


1 Answers

$fruits = array();
foreach ($arr as $key => $value) {
    if (strpos($key, 'fruit_') === 0) {
        $fruits[$key] = $value;
    }
}
like image 175
deceze Avatar answered Jan 07 '23 03:01

deceze