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 Answers2

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));
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
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');     
Blablaenzo
  • 1,027
  • 1
  • 11
  • 14