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)))
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));
0 comments:
Post a Comment