Named parameters are great for a long list of options in a PHP user defined function or class. But what about nested options?
Eg:
function foobar($foo,$bar,$options=array()) {
$default_options = array('option1'=>'','option2'=>'hello','option3'=>array('option1'=>true,'option2'=>''));
$options = array_merge($default_options,(array)$options);
}
So option 3 is another array with suboptions. Would we need to put them in a for loop to merge the suboptions too? What would you guys do in this case?
EDIT:
This is the function call:
foobar('foo','bar',array('option1'=>'foo','option3'=>array('option1'=>false)));
Ending structure for $options:
array(
'option1'=>'foo',
'option2'=>'hello',
'option3'=>array(
'option1'=>false,
'option2'=>''
);
Why not just use the func_get_args
function?
function yourFunction($keys) {
$default_options = array('test', array('test1' => array('test2')), 'test3');
$options = func_get_args();
array_shift($options);
$options = array_combine($keys, $options);
$options = array_merge($default_options, $options);
print_r($options);
}
// Usage
yourFunction(array('option1', 'option2', 'option3', 'option4'), 'optionval1', array('optionval2-1', 'optionval2-2'), 'optionval3', 4);
This way you have an array to start with and do not need to worry about anything else, and it can accept any number of parameters / arguments!
EDIT:
(Second edit, added the $keys as the first param) Modified the function above, here is the output. Not sure exactly what format of output you are looking for. So you may need to post the ending array structure you are after for your initial data given.
Array
(
[0] => test
[1] => Array
(
[test1] => Array
(
[0] => test2
)
)
[2] => test3
[option1] => optionval1
[option2] => Array
(
[0] => optionval2-1
[1] => optionval2-2
)
[option3] => optionval3
[option4] => 4
)