Wednesday 19 November 2014

How to pass variable number of arguments to a function in PHP?

In certain cases, you may require to pass different number of arguments to a function in PHP scripts. Let us consider a case where you want to calculate average of a set of values using a function. Number of values in the set may vary in each call to the function. PHP provides a mechanism to pass different number of arguments to a function and process the arguments from the function by using the following functions.

func_num_args() - Returns the number of arguments passes to the function

func_get_args() - Returns the arguments passed to the function as an array

func_get_arg($arg_num) - Returns the argument at the $arg_num th position or index . Starting index is 0.



You can see the PHP implementation of the above problem here.

varargs.php
<html>
    <head>       
        <title>How to pass variable number of arguments to a function in PHP?</title>
    </head>
    <body>               
            <?php          
               function calc_average() {
                            $args = func_get_args();
                            $sum = 0;
                            $avg = 0;
                            $num_args = func_num_args();
                              
                           foreach($args as $value){
                                  $sum +=$value;
                           }
               
                          if ($num_args>0)
                                $avg = $sum / $num_args;
                   
                          return $avg;               
             }











            echo "Average :" . calc_average(10,22,34,55);
            ?>
              
    </body>
</html>






No comments:

Post a Comment