Jump to content

Recommended Posts

Hi,

 

I have an array:

    $areas = array(
        "London" => "North",
        "London" => "South",
        "London" => "West",
        "Newcastle" => "North"
    );

I'm trying to loop around each one using the following:

foreach ($areas as $region => $city) {

        echo $city . "<br/>";

The results i'm getting is the bottom two. It seems like it wants unique ones.

West
North

I expected it to loop around them all and print north, south, west, north.

 

Can someone advise me how to write out each one? Why would it be skipping two values?

 

Thanks,

 

MoFish

Edited by MoFish
Link to comment
https://forums.phpfreaks.com/topic/300906-looping-an-array-problem/
Share on other sites

array indexes/keys must be unique. it's not skipping. when you define three elements with the same index/key, each new definition replaces the previous one.

 

depending on what you are trying to accomplish, you can make each array element have a region and city - 

$areas = array(
'region'=>"London", 'city' => "North",
'region'=>"London", 'city' => "South",
'region'=>"London", 'city' => "West",
'region'=>"Newcastle", 'city' => "North"
);

or you could make a sub-array under each region - 

$areas = array(
"London" => array("North","South","West"),
"Newcastle" => array("North")
);

Thank you for your reply. That explains why that was occouring.

 

I have changed my array to your first example - however the foreach seems like it needs tweeking

 

How would i amend this to display the results:

 

London - North

London - South

London - West

Newcastle - North

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.