PHP

Topic: Functions

How To Define a Function with Any Number of Arguments?

If you want to define a function with any number of arguments, you need to:    Declare the function with no argument.    Call func_num_args() in the function to get the number of the arguments.    Call func_get_args() in the function to get all the arguments in an array.Here is a PHP script on how to handle any number of arguments:<?phpfunction myAverage() {  $count = func_num_args();  $args = func_get_args();  $sum = array_sum($args);  return $sum/$count;  }$average = myAverage(102, 121, 105);print("Average 1: $average\n");$average = myAverage(102, 121, 105, 99, 101, 110, 116, 101, 114);print("Average 2: $average\n");?>This script will print:Average 1: 109.33333333333Average 2: 107.66666666667

Browse random answers: