-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
  • 491,798
  • 79
  • 706
  • 853
Nevermore
  • 1,562
  • 7
  • 26
  • 50

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
  • 18,131
  • 10
  • 32
  • 49