2

The main idea is that I want to convert this array:

$arr1 = ['user', 'address', 'street'];

To this one:

$arr2['user']['address']['street'];

I've been trying with recursive functions, foreach, for... but I couldn't figure out how to do it.

Example:

function appendingArrays($arrayOfKeys, $value) {
    // TODO
}
$finalArray = appendingArrays(['user', 'address', 'street'], 'Lombard Street');

echo $finalArray['user']['address']['street']; // Lombard Street

Any idea?

1

1 Answer 1

2

Hope this helps : Go Through Demo

[akshay@db1 tmp]$ cat test.php 
<?php

$arr1 = ['user', 'address', 'street'];

$c = count($arr1) - 1;
$out = array();
for($i = $c; $i >= 0; $i--)
{
    $out = array($arr1[$i] => $out);
}

/* input */  
print_r($arr1);

/* output */
print_r($out);

Output:

[akshay@db1 tmp]$ php test.php 
Array
(
    [0] => user
    [1] => address
    [2] => street
)
Array
(
    [user] => Array
        (
            [address] => Array
                (
                    [street] => Array
                        (
                        )

                )

        )

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.