In PHP, array is a very common data type. The data stored in the array can be numbers, strings, Boolean values, etc. When we need to perform some numerical operations on an array, such as finding the average, we need to use the related functions provided by PHP.
Let’s take a look at how to find the average in PHP.
First, we need to create an array to operate. Take an array containing a set of numbers as an example:
$nums = array(1, 2, 3, 4, 5);
Next, we need to sum the numbers in the array.
$sum = array_sum($nums); //求和
The above uses PHP's built-in array_sum() function, which can sum all elements in the array and return the result. Using this function is very simple, just pass it an array containing numbers.
Next, we need to count the number of elements in the array.
$count = count($nums); //计数
The count() function is used here, which can return the number of elements in the array. Again, we just need to pass it the array we want to count.
Finally, we can calculate the average by summing the result and the number of elements.
$avg = $sum / $count; //平均数
This statement divides the sum of the array elements by the number of elements to obtain the average.
Combining the above codes, you can get the following complete averaging code:
$nums = array(1, 2, 3, 4, 5); //创建数组 $sum = array_sum($nums); //求和 $count = count($nums); //计数 $avg = $sum / $count; //计算平均数 echo "平均数是:" . $avg; //输出结果
The output result of the above code is:
平均数是:3
Of course, if the array contains is a decimal, then calculating the average is simpler. You only need to change the last line of code to:
$avg = number_format($sum / $count, 2); //保留2位小数
number_format() function can retain the specified number of digits in the calculation result. The above code retains 2 decimal places and can be adjusted according to actual needs.
To summarize, in PHP, the steps to find the average of an array include: summing, counting, and calculating the average. We can use the related functions provided by PHP to complete these steps respectively. The above is this article's introduction to averaging in PHP arrays. I hope it will be helpful to everyone.
The above is the detailed content of Find average in php array. For more information, please follow other related articles on the PHP Chinese website!