PHP create key => value pairs within a foreach

PHP create key => value pairs within a foreach

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

Stefan Bogdanescu

Founder & Senior Architect

Building Associative Arrays Inside a foreach Loop

The core issue in the provided snippet isn't about array declaration scope; it's about how PHP handles key assignment when mixing indexed and associative structures. The goal is to construct an array where each element maps a specific $key from the source iterator to a value extracted at index [4].

Your current approach creates an intermediate variable $keyval inside the loop, which is then pushed onto $offerArray. While this technically works, it results in an indexed array containing associative arrays. The structure you described—where array[0] => key => value appears as triplets—is a classic symptom of nesting associative arrays into an indexed list rather than flattening them into a single associative map.

To achieve the flat associative structure (key => value) directly, you should assign the elements to $offerArray using the loop variable itself as the key. This eliminates the need for array_push, which always appends to the end of an array (creating indices 0, 1, 2...) and forces PHP to store nested arrays if you aren't careful with the assignment logic.

Direct Assignment Pattern

Instead of pushing a new array element onto $offerArray, assign the extracted value directly to the key provided by the loop. This ensures that the resulting structure is a single-level associative array.

function createOfferUrlArray($Offer) {
    $offerArray = [];

    foreach ($Offer as $key => $value) { 
        // Direct assignment creates a flat associative array
        $offerArray[$key] = $value[4]; 
    }

    return $offerArray;
}

In this implementation, $offerArray starts empty. On the first iteration, if $Offer has keys like id_101, the line $offerArray['id_101'] = 'some_url'; places that specific URL directly under that key. There is no intermediate array wrapper. The resulting structure matches your desired output exactly: a collection of unique keys mapping directly to their corresponding values.

Understanding the "Triplet" Issue

The confusion regarding "triplets" likely stems from how PHP visualizes nested arrays versus flat ones. When you use array_push with an inner associative array definition like array($key => $value[4]), you are explicitly telling PHP: "Add a new element to the list at the next available index (0, then 1), and make that element an associative array."

Visually, this looks like:

Array 
(
    [0] => Array ( [id_101] => value )
    [1] => Array ( [id_102] => value )
)

If your debugging output or library expects a flat associative map where keys are strings like id_101 rather than integers 0 and 1, the nested structure breaks downstream logic. By switching to direct assignment ($offerArray[$key] = ...), you bypass the integer index counter entirely. The array's internal pointer is managed by the specific string keys you provide, ensuring a clean, flat topology.

Performance Considerations

While array_push is convenient for appending data sequentially, it is generally slower than direct assignment when the key is known and available within the loop context. Direct assignment avoids the overhead of calculating the next integer index and resizing the underlying array structure repeatedly. For high-performance scripts processing large datasets, this distinction becomes measurable.

Furthermore, relying on array_push for associative data construction is an anti-pattern in PHP. It suggests that the developer is treating the data as a list (indexed) rather than a map (associative). If your intent is to preserve the original keys from $Offer while transforming the values, direct assignment is the semantic and syntactic choice.

When to Use array_map

If you find yourself writing loops solely for transformation without needing custom logic that depends on the key name itself, PHP's built-in array_map function offers a more concise alternative. It accepts a callback and applies it to every element in an array.

$offerArray = array_map(function($value) {
    return $value[4]; 
}, $Offer);

However, array_map preserves the original keys by default. If your input $Offer is already associative (e.g., it has keys like user_5, item_9) and you want to keep those specific keys while modifying the values, array_map works perfectly. If your input is indexed (0, 1, 2...) but you need to generate new keys based on content, a foreach with direct assignment remains the most flexible approach.

Conclusion

The solution lies in assigning values directly to the target array using the loop's key variable. This method produces a flat associative structure, avoids unnecessary nesting, and aligns with PHP best practices for data transformation.

Our network