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

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.

Program/Source Code:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.