dhad18 dhad18 - 1 year ago 47
PHP Question

Multidimensional array not returning the right values

I have a multidimensional array that I am trying to work with, here is what it looks like.

$states = array(
"California" => array(
"state" => "California",
"abbr" => "CA",
"city" => "Sacramento",
"county" => "Sacramento",
"zip" => "95632"
"Washington" => array(
"state" => "Washington",
"abbr" => "WA",
"city" => "Seattle",
"county" => "King",
"zip" => "98101"
"Texas" => array(
"state" => "Texas",
"abbr" => "TX",
"city" => "San Antonio",
"county" => "Bexar",
"zip" => "78251"
"Florida" => array(
"state" => "Florida",
"abbr" => "FL",
"city" => "Orlando",
"county" => "Orange",
"zip" => "32801"

When I run a foreach loop to get the keys from the first level of the arrays I get the expected output of

California Washington Texas Florida

However I need to access the second level of the array. For example I need California['abbr'] so this is the code I run:

foreach (array_keys($states) as $state) {
echo $state['abbr'];

Instead of getting


like I would expect I'm getting


Any ideas on what I'm doing wrong?

Answer Source

array_keys($states) is returning

 array("California", "Washington", "Texas", "Florida")

So the foreach loop is echoing just the first character of each state. Loop through the entire array instead of just the keys:

foreach ($states as $name => $details) {
    echo $details['abbr'];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download