PHP program to demonstrate the use of variable arguments

Here, we are going to demonstrate the use of variable arguments in PHP.
Submitted by Nidhi, on November 19, 2020 [Last updated : March 13, 2023]

Variable Arguments Example

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.

Example of variable arguments in PHP

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.

PHP Class & Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.