How to Generate a Default Function Parameter in PHP

In this snippet, we will have a look at the process of generating a default function parameter (also known as the optional parameter).

Generating and Using a Default Function Parameter

The syntax of this parameter is as follows:

function greeting($name = "parameter_value")

It is capable of accepting only one parameter (here it is the $name). It holds the value of the parameter.

The procedure of generating and using the default function parameter is illustrated in the examples below.

Example 1


function greeting($name = "W3docs")
  echo "Welcome to $name ";
  echo "\n";

// Passing no value
greeting("Computer Science Portal");

Welcome to W3d 
Welcome to W3docs 
Welcome to Computer Science Portal

Example 2


function welcome($first = "W3docs", $last = "Computer Science Portal for Everyone")
    echo "Greeting: $first $last";
    echo "\n";
welcome("night_fury", "Contributor");

Greeting: W3docs Computer Science Portal for Everyone
Greeting: night_fury Computer Science Portal for Everyone
Greeting: night_fury Contributor

About Default Function Parameter

The prototype of the concept of the default function parameter is C++ style default argument values.

In PHP, you can provide default parameters in a way that once a parameter is not passed toward the function, it is still reachable inside the function with a pre-defined value. Note that default values are also known as optional parameters, as it is not a must to pass them to the function.