Passing variable number of arguments to a function in PHP

We all know about functions and how we can pass arguments to it. But did you know that we can pass variable number of arguments in a function?

Consider a function sum() which adds numbers passed into its arguments. Now we want it to add all the numbers passed onto the arguments. Eg; if we call sum (21, 45) or sum (45, 23, 78, 56, 90) it should add all of them. Even if we pass a 100 arguments, it should execute successfully.

Below is the code for making the function sum() :

function sum() {
    $count = func_num_args();
     $sum = 0;
     for($i=0; $i<$count; $i++) {
         $num = func_get_arg($i);
         $sum += $num;
     }
     return $sum;
}

In above function func_num_args() give the total number of arguments that have been passed and func_get_arg() takes argument number as argument and returns the argument value.
We also have another function - func_get_args() which returns all the arguments passed to the function as an array.

For more information and examples on these functions:

func_num_args()
func_get_arg()
func_get_args()

Cheers!

Leave a comment

Your email address will not be published.