1

I want to create function which creates multidimensional array from parameter and second parameter should be saved as value here. Expected result is below:

Array
(
    [first] => Array
        (
            [second] => Array
                (
                    [last] => value
                )

        )

)

what I got so far :

 $array = ['first', 'second', 'last'];

    function multiArray($array, $newArray = [], $valueToSave)
    {
        if($array) {
            $value = current( $array );
            $key = array_search($value, $array);
            unset( $array[ $key ] );

            $newArray[$value] = [];
            return multiArray( $array, $newArray, $valueToSave);
        } else {
            return $newArray;
        }
    }

Any tips, what should I change or do next ?

1 Answer 1

1

You can try this simplest one.

Try this code snippet here

$array = ['first', 'second', "third", "fourth",'last'];
$value = "someValue";

$result = array();
$count = count($array);
for($x=$count-1;$x>=0;$x--)
{
    if($x==$count-1):
        $result[$array[$x]]=$value;//setting value for last index
    else:
        $tempArray = $result;//storing value temporarily
        $result = array();//creating empty array
        $result[$array[$x]] = $tempArray;//overriting values.
    endif;
}
print_r($result);
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly. Thank you.

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.