Passing Variable Parameters to a function

Passing Variable Parameters to a function

How to pass variable parameters to a function?
For example - define a generic function genAdd which will add all the parameters we passing.

$i = genadd(2,5);
$j = genadd(3,5,8);

So result of $i should be 7 and $j should be 16.

Fortunately PHP has following functions to achieve this.
func_get_args(); — This function will return array of argument list
func_get_arg(int arg_num); — This function will return an item from argument list.
func_num_args(); — This function will return number of arguments passed to a function

Implemetation

function genAdd(){
$sum = 0;
$args = func_get_args();

for($i = 0; $i < func_num_args(); $i++){
$sum += $args[$i];
}

return $sum;

}
$sum = genAdd(1,2,3);
echo $sum;
echo “<br>”;

$sum = genAdd(1,2,3,10,1);
echo $sum;

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.