In this example, we will calculate the average of some numbers using PHP.
We will create a function called sum_numbers to find the average of numbers. We will define the parameter that allows users to enter as many numbers as they want into this function using the … operator.
In the sum_numbers function, we will use array_sum function to find the sum of the numbers. We will devide the resulting value of the count of numbers using count fuction.
Then we will use return keyword to return the avarage of numbers.
PHP Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php #define function function sum_numbers(...$nums){ $sum = array_sum($nums); $avg = $sum / count($nums); return $avg; } #test $avg = sum_numbers(5,3,4,5,5,8); echo "Avarage of numbers : $avg <br>"; $avg = sum_numbers(1,2,3,4,5,6,7,8,9,10,11,12,13); echo "Avarage of numbers : $avg <br>"; |
Output:
1 2 3 4 | Avarage of numbers : 5 Avarage of numbers : 7 |