PHP Function Default Argument Values | PHP default parameters

PHP allows us to set default argument values for function parameters.

If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call.

Let’ see the simple example of using PHP default arguments in function.

Example

<?php

// function with default parameter
function defFunc($str, $num=16)
{
	echo "$str is $num years old <br>";
}

// Calling the function
defFunc("Peter", 15);

// In this call, the default value 12
// will be considered
defFunc("John");

?>
PHP default parameters example output

In the above example, the parameter $num has a default value 16, if we do not pass any value for this parameter in a function call then this default value 16 will be considered.

The parameter $str has no default value , so it is compulsory.

The default arguments must be constant expressions. They cannot be variables or function calls.

PHP allows you to use a scalar value, an array, and null as the default arguments.

Default parameters are optional.

The order of default parameters

When you use default parameters, you should place them after the parameters that don’t have default values. Otherwise, you will get unexpected behavior. For example:

<?php

function concat($delimiter = ' ', $str1, $str2)
{
	return $str1 . $delimiter . $str2;
}

$message = concat('Hi', 'there!', ',');

echo $message;
The order of default parameters example output