-3

For example user give me an array like this :

$input = ['countries', 'cities', 'towns'];

I want to create an array like this, i know what right side is :

$output["countries"]["cities"]["towns"] = "Downtown";

another example :

$input = ['cities', '0'];

$output["cities"][0] = "Nice";

I want to create a key / value array using the key given to me as a key.

I do not know the length of the array given to me.

deceze
  • 510,633
  • 85
  • 743
  • 889
Nevermore
  • 1,663
  • 7
  • 30
  • 56

1 Answers1

1

You could hold a reference of the last array in a loop :

$input = ['countries', 'cities', 'towns'];
$output = [];
$ref = &$output;
foreach ($input as $value) {
    $ref[$value] = [];
    $ref = &$ref[$value];
}
$ref="Downtown";
print_r($output);

Will outputs :

Array
(
    [countries] => Array
        (
            [cities] => Array
                (
                    [towns] => Downtown
                )
        )
)

Your second example :

$input = ['cities', '0'];
$output = [];
$ref = &$output;
foreach ($input as $value) {
    $ref[$value] = [];
    $ref = &$ref[$value];
}
$ref="Nice";
print_r($output);

Will outputs :

Array
(
    [cities] => Array
        (
            [0] => Nice
        )

)
Syscall
  • 19,327
  • 10
  • 37
  • 52