How to create default function parameter in PHP?

The default parameter concept comes from C++ style default argument values, same as in PHP you can provide default parameters so that when a parameter is not passed to the function. Then it is still available within the function with a pre-defined value. This function also can be called optional parameter.

Syntax:

function greeting($name=" parameter_value ")

Parameter: This function accepts a single parameter that is $name here, holds the parameter value.

Below examples illustrate the procedure to create and use the default function parameter:
Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php  
    function greeting($name="GeeksforGeeks")
    {  
        echo "Welcome to $name ";  
        echo("\n");
    }  
    greeting("Gfg"); 
  
    // Passing no value 
    greeting(); 
    greeting("A Computer Science Portal");  
?>  

chevron_right


Output:

Welcome to Gfg 
Welcome to GeeksforGeeks 
Welcome to A Computer Science Portal 

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php    
    function welcome($first="GeeksforGeeks",
                     $last="A Computer Science Portal for Geeks")
                     {    
                        echo "Greeting: $first $last";   
                        echo("\n");
    }    
    welcome();  
    welcome("night_fury");  
    welcome("night_fury","Contributer");  
?>    

chevron_right


Output:

Greeting: GeeksforGeeks A Computer Science Portal for Geeks
Greeting: night_fury A Computer Science Portal for Geeks
Greeting: night_fury Contributer



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.