Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add elements to an array in a loop using php

Tags:

arrays

php

I am dynamically trying to populate a multidimensional array and having some trouble.

I have a list of US states. Associative array like this $states[nc], $states[sc], etc. in my loop I want to append cities onto each state so $states[nc][cities] contains an array of cities. Im stuck with the logic.

foreach($states as $state) {
    $data[$state] = $state;

    foreach($cities as $city) {
      $data[$state]['cities'] .= $city;
     }
}

I know that concatenation is not correct, but I am not sure how to add elements to this array. I keep getting errors with array_push.

What's the correct way to add these elements?

like image 279
user658182 Avatar asked Mar 06 '12 10:03

user658182


Video Answer


1 Answers

The same way you add to an array when the key is not a concern:

$data[$state]['cities'][] = $city;
like image 105
Jon Avatar answered Sep 20 '22 19:09

Jon