Skip to content

PHP – Function that accepts array for arguments with defaults

If you have a PHP function that accepts a lot of arguments sometimes it would be easier just to pass those arguments into that function as an array, with the array keys acting as individual arguments.

If you create a function like this and then try to pass the array into it, it will not preserve all the default assigned keys.

function example($args = array(
    'foo'   => 'boom',
    'bar'   => 'pow'
)) {
    //
}

Here is a handy tool that allows you to have defaults.

/*
 * Required to set/merge array key/vals
 */
function parse_argument_array($args, $defaults='') {
 
    /* Check if Array is passes */
    if (is_array( $args )) {
        $arr =& $args;
    }
 
    else {
        /* parse_str converts string to array */
        parse_str($args, $arr);
    }
 
    /*
     *  If $defaults=array, merge missing/replaced
     *  http://php.net/manual/en/function.parse-str.php
     */
    if (is_array($defaults)) {
        return array_merge($defaults, $arr);
    }
 
    return $arr;
}
 
/*
 * Your function that accepts an array as an argument
 */
function function_with_argument_array($args='') {
 
    /*
     * Default Settings
     */
    $defaults = array(
        'foo'   => 'boom',
        'bar'   => 'pow'
    );
 
    $args = parse_argument_array($args, $defaults);
 
    return $args;
 
}
// On its own
print_r(function_with_argument_array());

Prints

Array
(
    [foo] => boom
    [bar] => pow
)
// With Arg
print_r(function_with_argument_array(array(
    'foo'   => 'bang'
)));

Prints

Array
(
    [foo] => bang
    [bar] => pow
)

About 

10 years + experience in web development working with lots of different technology.

Published inPHP

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *