7

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?

1
  • 2
    replacing the inner foreach with just $data[$state]['cities'] = $cities; should do the trick. Commented Mar 6, 2012 at 10:43

4 Answers 4

20

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

$data[$state]['cities'][] = $city;
Sign up to request clarification or add additional context in comments.

3 Comments

that did it! I was trying to overcomplicate it, but that gives me the correct result. Thanks!
@user9437856 yes, it's one line of code, it's not difficult to execute it and see.
@Jon, Thanks for the reply. I was trying to implement your issue here : stackoverflow.com/questions/61977036/…
17

In PHP, you can fill an array without referring to the actual index.

$newArray = array();
foreach($var in $oldArray){
$newArray[] = $var;
}

2 Comments

Much simpler syntax: $newArray = array_values($oldArray);
foreach() with in? Nope. 3v4l.org/0vmXZ
4

To add an element, use empty brackets.

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

This will create an array like this

array(
  'nc' => array('city1', 'city2', ...),
  'sc' => array('city1', 'city2', ...)
)

See manual under "Creating/modifying with square bracket syntax"

Comments

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

    foreach($state->cities as $city) {
      $data[$state][] = $city;
    }
}

Using empty brackets adds an element to the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.