How to pass random length of a function in php?

Member

by lew , in category: PHP General , 6 months ago

How to pass random length of a function in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 6 months ago

@lew 

In PHP, you can pass a variable number of arguments to a function by using the func_get_args() function. This function retrieves all the arguments passed to the function and returns them as an array.


Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function sum() {
    $args = func_get_args();
    $total = 0;
    
    foreach ($args as $arg) {
        $total += $arg;
    }
    
    return $total;
}

$result1 = sum(1, 2, 3); // 6
$result2 = sum(4, 5, 6, 7); // 22


In the above example, the sum() function accepts any number of arguments. The func_get_args() function is used to retrieve all the arguments passed to the function, and then a loop is used to calculate the sum of all the arguments.


By using func_get_args(), you can pass a random length of arguments to the function without having to specify them individually in the function declaration.