-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.

0

1 Answer 1

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
        )

)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.