2

My goal is to write a function which would assign a value to any multidimensional array:

function array_multidim_set($arr, $keys, $value)

Example: print_r(array_multidim_set($arr, ['key1', 'key2', 'key'3'], 'foo') should create a value as following $arr[key1][key2][key3] = 'foo';

For now I'm using this:

function array_multidim_set($arr, $keys, $value){
    switch(count($keys)){
        case 1:
           $arr[$keys[0]] = $value;
           break;
        case 2:
           $arr[$keys[0]][$keys[1]] = $value;
           break;
        case 3:
           $arr[$keys[0]][$keys[1]][$keys[2]] = $value;
           break;

        ...and so on...

    }

    return $arr;
}

But it's limited to the amount of cases defined. Is there any way to make a universal function for any amount of keys?

Thank you!

1 Answer 1

3

try below solution:

function array_multidim_set(&$arr, $keys, $value){
    $rv = &$arr;
    foreach($keys as $pk)
    {
        $rv = &$rv[$pk]; // Unused reference [ex. $rv['key1'] then $rv['key1']['key2'] .. so on ] - actually assigned to $target by reference
    }
    $rv = $value;
}

$target = ['test' => 'test'];

array_multidim_set($target, ['key1', 'key2', 'key3'], 'foo');
echo '<pre>';
print_r($target);

Output:

Array
(
    [test] => ttt
    [key1] => Array
        (
            [key2] => Array
                (
                    [key3] => foo
                )

        )

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

2 Comments

That is really awesome! Thanks!
Thanks @DainiusVaičiulis

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.