"apple", "...">

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.

+4
source share
4 answers
 $fruits = array(); foreach ($arr as $key => $value) { if (strpos($key, 'fruit_') === 0) { $fruits[$key] = $value; } } 
+5
source

One solution:

 foreach($arr as $key => $value){ if(strpos($key, "fruit_") === 0) { ... ... } } 

=== ensures that the string was found at position 0, since strpos can also return FALSE if the string is not found.

+3
source

You are trying:

 function filter($var) { return strpos($var, 'fruit_') !== false; } $arr = array( "fruit_aac"=>"apple", "fruit_2de"=>"banana", "fruit_ade"=>"grapes", "other_add"=>"sugar", "other_nut"=>"coconut", ); print_r(array_flip(array_filter(array_flip($arr), 'filter'))); 
+3
source

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

+2
source

Source: https://habr.com/ru/post/1414674/


All Articles