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
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";
}
Link to comment
Share on other sites

@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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.