Reputation: 652
I have a function that takes an "Options" argument array for setting flags for querying a database. It looks like this
function c_SQL($SQL='', $FIELDS=array(), $OPTIONS=array('SINGLEROW'=>false,'foo'=>false,'bar'=>false)) {
}
I am trying to maintain the default array keys if I do not set them in my function call:
$test = c_SQL($query,$fields,array('SINGLEROW'=>true));
This is generating an error inside the c_SQL function when we do checks against the array keys not specified (foo and bar).
Is there a way to maintain 'foo' and 'bar' if not specified and only change the keys only if passed into the function?
Upvotes: 2
Views: 212
Reputation: 311188
You could hold the defaults as a constant, and use array_merge
to apply them to the user's input:
$DEFAULT_OPTIONS = array('SINGLEROW'=>false,'foo'=>false,'bar'=>false);
function c_SQL($sql='', $fields=array(), $options=array()) {
$actual_options = array_merge($default_options, $options);
}
Upvotes: 3
Reputation: 506
You can use array_merge
inside the function to merge with a defaults array defined inside the function.
function c_SQL($SQL = '', $FIELDS=array(), $OPTIONS = array()) {
$defaults = array(
'SINGLEROW' => false,
'foo' => false,
'bar' => false
);
$OPTIONS = array_merge($defaults, $OPTIONS);
return $OPTIONS;
}
# array ( 'SINGLEROW' => false, 'foo' => false, 'bar' => false, )
var_export(c_SQL());
# array ( 'SINGLEROW' => true, 'foo' => false, 'bar' => false, )
var_export(c_SQL(array('SINGLEROW' => true)));
Upvotes: 5
Reputation: 927
Try assigning $OPTIONS
as null
or empty array and then check in function check if it is null or not, if its null then assign the array. Take a look at it here..
function c_SQL($SQL='', $FIELDS=array(), $OPTIONS=NULL) {
if(empty($OPTIONS) {
$OPTIONS=array('SINGLEROW'=>false,'foo'=>false,'bar'=>false)
} else {
$othervalues = array('SINGLEROW'=>false,'foo'=>false,'bar'=>false);
$OPTIONS = array_merge($othervalues, $OPTIONS);
//do something here
}
}
Upvotes: 1
Reputation: 6778
Create your default options inside the function body and then merge your new options with array_merge
function c_SQL($SQL='', $FIELDS=array(), $OPTIONS=array()) {
$DEFAULTS = array('SINGLEROW'=>false,'foo'=>false,'bar'=>false);
$OPTIONS = array_merge($DEFAULTS, $OPTIONS);
}
Upvotes: 1