Home > other >  I cannot figure out the solution for this problem
I cannot figure out the solution for this problem

Time:07-25

Write a program which includes a function sum. This function sum should be designed to add an arbitrary list of parameters. (For e.g., if you call the function sum() as sum (1, 2) it should return the result 3 and if again you call the function sum() as sum(1,3,4) it should return the result 8

CodePudding user response:

You can use func_get_args and do a foreach on the arguments, summing them and returning the value.

function sum()
{
    $arg_list = func_get_args();
    $total = 0;
    for ($i = 0; $i < count($arg_list); $i  ) {
        $total  = $arg_list[$i];
    }
    return $total;
}

CodePudding user response:

This is a variable length parameter.

https://www.javatpoint.com/php-variable-length-argument-function#:~:text=PHP supports variable length argument,length argument since PHP 5.6.

  •  Tags:  
  • php
  • Related