Home »
PHP »
PHP programs
PHP program to demonstrate the use of default arguments
Here, we are going to demonstrate the use of default arguments in PHP.
Submitted by Nidhi, on November 19, 2020 [Last updated : March 13, 2023]
Default Arguments Example
Here, we will calculate the addition of two numbers, here we use on the argument of user define function contains a default value. It means if we will pass the value of the default argument then the default value is used for that parameter.
Example of default arguments in PHP
The source code to demonstrate the use of default arguments is given below. The given program is compiled and executed successfully.
<?php
//PHP program to demonstrate the
//use of default arguments.
function Sum($num1, $num2 = 20)
{
$num3 = $num1 + $num2;
return $num3;
}
$num3 = Sum(10, 30);
echo "Sum: " . $num3 . "<br>";
$num3 = Sum(10);
echo "Sum: " . $num3 . "<br>";
?>
Output
Sum: 40
Sum: 30
Explanation
In the above program, we created a user define function Sum() that contains two arguments $num1 and $num2.
function Sum($num1, $num2=20);
Here, we used $num2 as a default argument, if we pass only one value to the function then 20 will be used for $num2.
$num3=Sum(10,30);
echo "Sum: ".$num3."<br>";
In the above code, we pass two arguments then the sum of 10 and 30 assigned to the variable $num3 and printed on the webpage.
$num3=Sum(10);
echo "Sum: ".$num3."<br>";
In the above code, we pass only one argument then the sum of 10 and 20 assigned to the variable $num3 and printed on the webpage.
PHP Class & Object Programs »