user2982427
user2982427

Reputation:

Accessing multidimensional arrays in php

A simple example where states is an array of states and each state is an array of cities. Trying to access $states[0] to $states[n] works but in a for loop echoes empty values.

$states = array(
'California' => array('LA', 'San Diego', 'San Francisco'),
'Arizona' => array('Phoenix'),
'Florida' => array('Miami', 'Jacksoncille', 'Tampa', 'Orlando'),
'Ohio' => array('Cincinnati', 'Columbus')
);

$arrlength = count($states);

for($x=0;$x<$arrlength;$x++) {

echo '<h2>'.$states[$x].'</h2>'; //returns 4 empty h2

}

Upvotes: 0

Views: 61

Answers (5)

sumith
sumith

Reputation: 129

As everyone says foreach is the best way to go through an array since the boundaries are are undefined and keys are non-numeric. Anyway if you still wants to do with a for loop this may be helpful. But it's very silly and may cause problems later.

$states = array(
    'California' => array('LA', 'San Diego', 'San Francisco'),
    'Arizona' => "cc",
    'Florida' => array('Miami', 'Jacksoncille', 'Tampa', 'Orlando'),
    'Ohio' => array('Cincinnati', 'Columbus')
);


$state_array = array_keys($states);
$city_array = array_values ($states);


for($x=0;$x<count($state_array);$x++) {
    echo "<b>";echo $state_array[$x];echo "</b>";echo "<hr>";
    if(is_array($city_array[$x])){
        for($y=0;$y<count($city_array[$x]);$y++){
            echo $city_array[$x][$y];echo "</br>";      
        }
    }else{
        echo $city_array[$x];echo "</br>";      
    }
    echo "</br>";
}

Upvotes: 0

marian0
marian0

Reputation: 3337

You don't have numerical indexes in your array, because it's associative array. So you can e.g. call $states['Arizona'], but you can't call $states[1].

To foreach over use foreach loop:

foreach ($states as $name => $cities) {
    echo $name;
    foreach ($cites as $city) {
        echo $city;
    }
}

Upvotes: 0

Domain
Domain

Reputation: 11808

$states = array(
'California' => array('LA', 'San Diego', 'San Francisco'),
'Arizona' => array('Phoenix'),
'Florida' => array('Miami', 'Jacksoncille', 'Tampa', 'Orlando'),
'Ohio' => array('Cincinnati', 'Columbus')
);

foreach($states as $key=>$val)
{
echo $key;
foreach($val as $value)
   echo '<h2>'.$value.'</h2>';
}

Upvotes: 1

rvandoni
rvandoni

Reputation: 3407

You should use a foreach. Try with this:

    foreach($states as $state_name => $cities) {
        echo '<h2>'.$state_name .'</h2>';
        foreach($cities as $city) {
            echo "<h3>".$city."</h3>"
        }
    }

Upvotes: 0

SeanWM
SeanWM

Reputation: 17009

It's because you're defining the keys. Try a foreach loop instead:

foreach($states as $key => $value) {
    echo $key . '-' . $value;
}

Where $key will be the state and $value will be the city.

Upvotes: 1

Related Questions