Skip to content
Advertisement

Add new dimension to array in php [closed]

I don’t know how to ask the question.My goal is :

convert :

$myArr = ['a', 'b', 'c', ....];

into :

$newArr['a']['b']['c']... = 1;

Advertisement

Answer

Start with the value to be assigned, then for-loop backwards over the array:

$arr = [ 'a', 'b', 'c', 'd' ];

$result = 1;

for ($i = count($arr) - 1; $i >= 0; $i--) {
  $result = [ $arr[$i] => $result ];
}

print_r($result);

Output:

Array
(
    [a] => Array
        (
            [b] => Array
                (
                    [c] => Array
                        (
                            [d] => 1
                        )

                )

        )

)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement