Here, we will calculate the addition of arguments, here we will use a variable number of arguments in the user define a function using ... (three dots). Here, we can pass any number of arguments to the function.
The source code to demonstrate the use of variable arguments is given below. The given program is compiled and executed successfully.
<?php
//php program to demonstrate the
//use of variable arguments.
function Sum(...$values)
{
$res = 0;
foreach ($values as $val)
{
$res = $res + $val;
}
return $res;
}
$sum = Sum(10, 20);
echo "Sum: " . $sum . "<br>";
$sum = Sum(10, 20, 30);
echo "Sum: " . $sum . "<br>";
?>
Output:
Sum: 30
Sum: 60
Explanation:
In the above program, we created a function that accepts a variable number of arguments, here we can pass the different number of arguments in the different calls of the function. Here we accessed arguments values using the foreach loop and add to the $res variable and return the value of $res to the calling function.
$sum=Sum(10,20);
echo "Sum: ".$sum."<br>";
In the above code, we passed two arguments and print the sum of both on the webpage.
$sum=Sum(10,20,30);
echo "Sum: ".$sum."<br>";
In the above code, we passed three arguments and print the sum of all on the webpage.
Program/Source Code:
The source code to demonstrate the use of variable arguments is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created a function that accepts a variable number of arguments, here we can pass the different number of arguments in the different calls of the function. Here we accessed arguments values using the foreach loop and add to the $res variable and return the value of $res to the calling function.
In the above code, we passed two arguments and print the sum of both on the webpage.
In the above code, we passed three arguments and print the sum of all on the webpage.
need an explanation for this answer? contact us directly to get an explanation for this answer