PHP Default Function Parameter values, how to ‘pass default value’ for ‘not last’ parameters?

PHP doesn’t support what you’re trying to do. The usual solution to this problem is to pass an array of arguments:

function funcName($params = array())
{
    $defaults = array( // the defaults will be overidden if set in $params
        'value1' => '1',
        'value2' => '2',
    );

    $params = array_merge($defaults, $params);

    echo $params['value1'] . ', ' . $params['value2'];
}

Example Usage:

funcName(array('value1' => 'one'));                    // outputs: one, 2
funcName(array('value2' => 'two'));                    // outputs: 1, two
funcName(array('value1' => '1st', 'value2' => '2nd')); // outputs: 1st, 2nd
funcName();                                            // outputs: 1, 2

Using this, all arguments are optional. By passing an array of arguments, anything that is in the array will override the defaults. This is possible through the use of array_merge() which merges two arrays, overriding the first array with any duplicate elements in the second array.

Leave a Comment