0

I need a function like this one:

function multi(){
    $args = get_func_args();
    $array = ????
    return $array;
}
print_r(multi('foo','bar','baz',123));
// expected result: array([foo] => array([bar] => array([baz] => 123)))
2
  • Does it have to be a list of args passed in or can you pass in an array? print_r(multi(array('foo','bar','baz',123))); Commented Feb 10, 2015 at 21:29
  • whatever I think.. $args in function has the args as an array. Commented Feb 10, 2015 at 21:33

2 Answers 2

1

I've answered multiple variations of this using a reference to build-up the array:

function multi() {
    $path = func_get_args();      //get args
    $value = array_pop($path);    //get last arg for value

    $result = array();            //define our result
    $temp = &$result;             //reference our result

    //loop through args to create key
    foreach($path as $key) {
        //assign array as reference to and create new inner array
        $temp =& $temp[$key];
    }
    $temp = $value;               //set the value

    return $result;
}

print_r(multi('foo','bar','baz',123));
Sign up to request clarification or add additional context in comments.

2 Comments

Yep, also see here for maybe a better way, though the func_get_args is cool as well: stackoverflow.com/questions/27929875/…
Now I get your link. Perfect!
0

This will also work:

    function multi(){
        $array = null;
        $args = func_get_args();
        while(count($args)>0) {
            $last = array_pop($args);
            $array = $array ? array($last=>$array) : $last;
        }
        return $array;
    }
    $data = multi('foo','bar','baz',123);

to update an existing value (no checks if items really exists)

    function set_multi($val, &$target){
        $args = array_slice(func_get_args(), 2);
        while(count($args)>0) {
            $first = array_shift($args);
            $target = &$target[$first];
        }
        $target = $val;
    }
    set_multi(456, $data, 'foo', 'bar', 'baz');     

1 Comment

Good!.. How can I update a global multi array like $array['foo']['jojo']['test'] = 345?

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.