PHP: Using optional default parameters in a function.

This is a guide on how to use optional / default function parameters in PHP. In other languages such as Java, you can use a feature called Method Overloading. However, in PHP, two functions cannot have the same name.

Optional parameters are useful because they allow us to control how a function is executed if a certain parameter has been omitted from the function call.

Example of a PHP function that has default arguments.

Let’s take a look at the following example:

/**
 * A function that returns an array
 * of animals.
 *
 * @param bool $sort Optional parameter.
 * @return array
 */
function getAnimals($sort = false){
    $animalsArray = array(
        'Dog', 'Cat', 'Zebra', 'Horse'
    );
    if($sort === true){
        sort($animalsArray);
    }
    return $animalsArray;
}

The function above has one parameter called $sort. By default, $sort is set to a boolean FALSE value. As a result, our $sort parameter will default to FALSE if the getAnimals function is called without any arguments.

You can test this out by running the following PHP snippet:

//Calling the function without specifying
//the default parameter.
$animals = getAnimals();
var_dump($animals);

//Calling the function with the
//default parameter.
$animals = getAnimals(true);
var_dump($animals);

In the first function call, we omitted the first parameter. This means that $sort will default to FALSE:

unsorted php array

As you can see, the array above has not been sorted.

However, in the second function call, we did provide an argument. This means that our default parameter is overridden:

sorted php array

In the screenshot above, you can see that the array has been sorted in alphabetical order.

Multiple default parameters.

PHP functions can have multiple default parameters. Take the following example:

//Example of a PHP function that has multiple
//default parameters
function my_function($a = false, $b = true, $c = null){
    //do something
}

The PHP function above has three parameters, all of which have their own default values:

  • $a has a default value of FALSE.
  • $b has been set to TRUE.
  • $c is NULL by default.

As a result, you can call the function above like so:

//Calling the function without providing
//any parameters.
my_function();

You can also provide only one of the three optional arguments:

//Only providing the first parameter.
my_function(true);

The function call above will result in the first parameter $a being set to TRUE.

But what if we only wanted to change the last optional argument? Well, in that case, we need to provide all of the function’s arguments while making sure that the default values of the first two parameters aren’t changed:

//Changing the last parameter.
my_function(false, true, 'test');

In the example above, we used the default values of the first two parameters while changing the third.

Hopefully, you found this tutorial useful!