MoFish Posted February 28, 2016 Share Posted February 28, 2016 (edited) 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 February 28, 2016 by MoFish Quote Link to comment Share on other sites More sharing options...
mac_gyver Posted February 28, 2016 Share Posted February 28, 2016 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") ); Quote Link to comment Share on other sites More sharing options...
MoFish Posted February 28, 2016 Author Share Posted February 28, 2016 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 Quote Link to comment Share on other sites More sharing options...
Jacques1 Posted February 28, 2016 Share Posted February 28, 2016 I strongly recommend that you learn how arrays work, because this is fundamental for any programming language, not just PHP. If you still can't get it to work, post your code and explain the problem. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.