Choosing an element in an associative array differently in PHP
Ok I have such an associative array in PHP
$arr = array( "fruit_aac" => "apple", "fruit_2de" => "banana", "fruit_ade" => "grapes", "other_add" => "sugar", "other_nut" => "coconut", );
now I want to select only those elements that begin with the fruit_
key. How is this possible? Can regex be used? or any PHP array functions? Is there a workaround? Please give some examples for your solutions.
If you want to try regex, you can try the code below ...
$arr = array("fruit_aac"=>"apple", "fruit_2de"=>"banana", "fruit_ade"=>"grapes", "other_add"=>"sugar", "other_nut"=>"coconut", ); $arr2 = array(); foreach($arr AS $index=>$array){ if(preg_match("/^fruit_.*/", $index)){ $arr2[$index] = $array; } } print_r($arr2);
I hope this will be helpful to you.
thanks