It is necessary to bring into a separate array of all animals, whose names consist of 2 words.

$animals = array( "Africa" => array('Elephants','Gorilla'), "Australia" => array('Kangaroo','Koala bear'), "South America" => array('Panthera onca','Anaconda'), "North America" => array('Haliaeetus leucocephalus','Gray Wolf'), "Asia" => array('Ailuropoda melanoleuca','Bengal Tiger'), "Europe" => array('Bos primigenius','Wolverine'), "Antarctica" => array('Aptenodytes forsteri','Aptenodytes patagonica'), ); 

How can I do that? Thanks in advance.

  • I tried to deduce using the explode method, but I could not, because I still don’t understand how it all works. - Bulat

1 answer 1

 $result = []; foreach ($animals as $countinent) { $result = array_merge($result, array_filter($countinent, function ($item){ return count(explode(' ', $item)) === 2; }) ); } print_r($result); 
  • If you write in one line, the code looks cooler (no) - sscream
  • To be honest, in PHP, in contrast to JS, the function call is used instead of the method call of the Array object, so the result is quite a lengthy verbose structure, with a certain nesting, and I have not yet learned how to make such structures so that the code looks cool. - Ivan Tsyganenko
  • I figured it out, everything works!) - Bulat