Jump to content

php array and foreach loop


ahsn

Recommended Posts

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

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";
}

@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? 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.