ahsn Posted July 26, 2013 Share Posted July 26, 2013 I have this array: <?php $continents=array("Asia"=>array("Bangladesh","India","Pakistan"), "Europe"=>array("England","France"), "Africa"=>array("Kenya","Libya","Somalia")); ?> Now I would like to echo: In Africa there are: Kenya, Libya, Somalia. How can I do that? Can anyone please help me? Thanks in advance. Link to comment https://forums.phpfreaks.com/topic/280542-php-array-and-foreach-loop/ Share on other sites More sharing options...
AbraCadaver Posted July 26, 2013 Share Posted July 26, 2013 foreach($continents as $continent => $countries) { echo $continent; foreach($countries as $country) { echo $country; } } Or if you just want Africa, foreach over $continents['Africa'] Link to comment https://forums.phpfreaks.com/topic/280542-php-array-and-foreach-loop/#findComment-1442277 Share on other sites More sharing options...
Psycho Posted July 26, 2013 Share Posted July 26, 2013 Since you want the list of countries to be concatenated with a comma, you could just implode() the countries instead of doing a second foreach() loop. foreach($continents as $continent => $countries) { $countriesList = implode(', ', $countries); echo "In {$continent} there are: {$countriesList}.<br>\n"; } Link to comment https://forums.phpfreaks.com/topic/280542-php-array-and-foreach-loop/#findComment-1442282 Share on other sites More sharing options...
ahsn Posted July 26, 2013 Author Share Posted July 26, 2013 @AbraCadaver, thank you for your help, but that echos all the countries. I ONLY want to echo this line: 'In Africa there are: Kenya, Libya, Somalia.' I tried but couldn't. @Psycho, thank you for your help, though it echos all the continents and countries, your codes look promising but I want to echo ONLY this line: 'In Africa there are: Kenya, Libya, Somalia.' Can you please alter the codes to do that? Link to comment https://forums.phpfreaks.com/topic/280542-php-array-and-foreach-loop/#findComment-1442316 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.