How to Generate a Default Function Parameter in PHP
In this snippet, we will have a look at the process of generating and using 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:
How to Generate a Default Function Parameter in PHP
function greeting($name = "parameter_value")It is capable of accepting only one parameter (here it is the <kbd class="highlighted">$name</kbd>). 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
Example of generating a default function parameter in PHP
<?php
function greeting($name = "W3docs")
{
echo "Welcome to $name ";
echo "\n";
}
greeting("W3d");
// Passing no value
greeting();
greeting("Computer Science Portal");
?>create and use php default function parameter, outcome
Welcome to W3d
Welcome to W3docs
Welcome to Computer Science PortalExample 2
php create and use default function parameter
<?php
function welcome($first = "W3docs", $last = "Computer Science Portal for Everyone")
{
echo "Greeting: $first $last";
echo "\n";
}
welcome();
welcome("night_fury");
welcome("night_fury", "Contributor");
?>php default function parameter, output
Greeting: W3docs Computer Science Portal for Everyone
Greeting: night_fury Computer Science Portal for Everyone
Greeting: night_fury ContributorAbout 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.