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

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.

Program/Source Code:

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.






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.