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

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

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Building Multidimensional Arrays in PHP Loops

A common stumbling block when working with PHP data structures is attempting to nest loops while trying to mutate an array's structure on the fly. The specific scenario described involves taking a flat list of states and populating each one with a corresponding list of cities, resulting in a multidimensional array where $states['nc']['cities'] holds an array of city names.

The core issue in the provided code snippet lies in two distinct mistakes: using string concatenation on an undefined key and misunderstanding how to initialize nested arrays. When you execute $data[$state]['cities'] .= $city, PHP attempts to treat the value at that index as a string because of the dot operator (.). However, since ['cities'] has not been initialized yet, PHP creates it as a null or empty string depending on context, but even if it existed, appending a city name like "Charlotte" directly to another would result in "CharlotteRaleigh", which is clearly incorrect for data storage. You are trying to build an array of items, not a single long string.

Furthermore, the logic $data[$state] = $state; inside the outer loop creates a copy of the state name as the value, but it fails to establish the nested structure required to hold the cities. To fix this, you must explicitly initialize the inner array before attempting to add elements to it. The most idiomatic and performant way to do this in PHP is using [] to create an empty array immediately upon assignment.

Here is the corrected approach for a standalone script:

// Assume $states is ['nc' => true, 'sc' => true] and $cities is ['Charlotte', 'Raleigh']

$states = [
    'nc' => ['cities' => []],
    'sc' => ['cities' => []],
];

$cities = ['Charlotte', 'Raleigh', 'Greenville'];

foreach ($states as $stateKey => $stateData) {
    foreach ($cities as $city) {
        // Initialize the array if it doesn't exist to prevent string concatenation errors
        if (!isset($stateData['cities'])) {
            $stateData['cities'] = [];
        }

        // Add the city to the specific state's cities array
        $stateData['cities'][] = $city;
    }
}

In this pattern, we iterate over the keys of the $states array. Inside the loop, we ensure that cities is initialized as an empty array before pushing data into it. Once the container exists, we use the square bracket syntax with [] to push new elements. This automatically appends the item to the end of the existing array without needing to calculate indices manually.

If you are working within a Laravel application, the mental model remains identical because PHP's core array functions behave consistently regardless of the framework. However, if you find yourself managing complex nested data structures frequently, consider using collect() from the Laravel collection helper. It provides a fluent interface that can make these operations more readable:

$states = collect(['nc', 'sc']);
$cities = ['Charlotte', 'Raleigh'];

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

There is a subtle performance consideration here. While modern PHP engines handle dynamic array resizing efficiently, repeatedly calling array_push() or using the [] syntax in tight loops inside nested iterations can be slightly slower than calculating an index offset if you know exactly how many items will be added beforehand. In most application logic, however, this optimization is negligible compared to I/O operations like database queries.

The primary pitfall to avoid is relying on string concatenation (.=) when your intent is to build a collection. Always check whether the target key exists before trying to append to it, or initialize it immediately if you know the structure ahead of time. This prevents type errors where an integer or string might accidentally be appended to a numeric index instead of a list.

Our network