Friday, September 5, 2025
HomeLanguagesHow to create optional arguments in PHP ?

How to create optional arguments in PHP ?

Arguments that do not stop the function from working even though there is nothing passed to it are known as optional arguments. Arguments whose presence is completely optional, their value will be taken by the program if provided. But if no value is given for a certain argument, the program will not halt. These arguments are given rise by usually providing the function with a default value for the parameter. Now, if the function is given with the value of the argument during the call, the given arguments overwrite the default one and the program continues normally. But if the call doesn’t provide the function with any value, the program continues normally with the default ones.

The idea here is to create such optional arguments within are program. This will as mentioned will be carried out using the default value.

Flow chart: Although the concept is pretty straight-forward but here is a flow chart to understand better.

Below examples illustrate the optional arguments in PHP.

Example 1:




<?php
function travel($place = "Sweden")
{
  return "Traveling to $place.\n";
}
echo travel();
echo travel("Australia");
echo travel("Tokyo");
?>


Output:

Travelling to Sweden. 
Traveling to Australia. 
Traveling to Tokyo.

Example 2: In this example it confirms that the timer is set.




<?php
function timer($hour=00, $min=00, $sec=00)
  $time="$hour : $min : $sec.";
  return "Timer set for $time \n";
}
echo timer();
echo timer(10, 30, );
echo timer(00, 20, 40);
?>


Output:

Timer set for 0 : 0 : 0. 
Timer set for 10 : 30 : 0. 
Timer set for 0 : 20 : 40.
RELATED ARTICLES

Most Popular

Dominic
32267 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6635 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7026 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6720 POSTS0 COMMENTS