Summary: In this tutorial, you’ll learn about PHP default parameters and how to use them to simplify function calls.
Introduction to the PHP default parameters #
The following defines the concat()
function that concatenates two strings with a delimiter:
<?php
function concat($str1, $str2, $delimiter)
{
return $str1 . $delimiter . $str2;
}
Code language: HTML, XML (xml)
When you call the concat()
function, you need to pass exactly three arguments. For example:
<?php
function concat($str1, $str2, $delimiter)
{
return $str1 . $delimiter . $str2;
}
$message = concat('Hi', 'there!', ' ');
echo $message;
Code language: HTML, XML (xml)
However, you’ll find that you often use the space ‘ ‘ as the delimiter. And it’s repetitive to pass the space whenever you call the function.
This is why default parameters come into play.
PHP allows you to specify a default argument for a parameter. For example:
<?php
function concat($str1, $str2, $delimiter = ' ')
{
return $str1 . $delimiter . $str2;
}
Code language: HTML, XML (xml)
In this example, the $delimiter
parameter takes the space as the default argument.
When you call the concat()
function and don’t pass the delimiter argument, the function will use the space for the $delimiter
like this:
<?php
function concat($str1, $str2, $delimiter = ' ')
{
return $str1 . $delimiter . $str2;
}
$message = concat('Hi', 'there!');
echo $message;
Code language: HTML, XML (xml)
Output:
Hi there
However, if you pass an argument for the $delimiter
, the function will use that argument instead:
<?php
function concat($str1, $str2, $delimiter = ' ')
{
return $str1 . $delimiter . $str2;
}
$message = concat('Hi', 'there!', ',');
echo $message;
Code language: HTML, XML (xml)
Output:
Hi,there!
In this example, we passed a comma to the $delimiter
. The concat()
function used the comma (,
) instead of the default argument.
When you specify a default argument for a parameter, it becomes optional. This means that you can pass a value or skip it.
Default arguments #
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.
The order of default parameters #
When you use default parameters, it’s a good practice to 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;
Code language: HTML, XML (xml)
Output:
there!Hi,
Summary #
- Use default parameters to simplify the function calls.
- Default parameters are optional.