How to build dynamic associative array from simple array in php?

In PHP, you can build a dynamic associative array from a simple array by iterating through the array in reverse order and creating nested associative arrays. This technique is useful when you need to transform a flat array into a hierarchical structure.

Syntax

The basic approach involves using array_reverse() to process elements from the last to the first, building nested arrays progressively ?

function buildDynamicArray($array, $value) {
    if (empty($array)) {
        return $value;
    }
    
    foreach (array_reverse($array) as $key) {
        $result = [$key => $value];
        $value = $result;
    }
    
    return $result;
}

Example

Here's how to transform a simple array into a nested associative array ?

<?php
function buildingDynamicAssociativeArray($nameArr, $lastName) {
    if (!count($nameArr)) {
        return $lastName;
    }
    
    foreach (array_reverse($nameArr) as $key) {
        $dynamicAssociativeArr = [$key => $lastName];
        $lastName = $dynamicAssociativeArr;
    }
    
    return $dynamicAssociativeArr;
}

// Example 1: Normal array
$namesArray = ['John', 'Adam', 'Robert'];
$result = buildingDynamicAssociativeArray($namesArray, 'Smith');
print_r($result);

echo "<br>";

// Example 2: Empty array
$namesArray = [];
$result1 = buildingDynamicAssociativeArray($namesArray, 'Doe');
print_r($result1);
?>
Array
(
    [John] => Array
        (
            [Adam] => Array
                (
                    [Robert] => Smith
                )

        )

)

Doe

How It Works

The function works by reversing the input array and iterating through each element. For each iteration, it creates a new associative array where the current element becomes the key and the previous result becomes the value. This builds the nested structure from the inside out.

Conclusion

Building dynamic associative arrays from simple arrays is achieved by reversing the array and iterating to create nested structures. This technique is particularly useful for creating hierarchical data structures from flat arrays.

Updated on: 2026-03-15T09:30:11+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements