Home >Backend Development >PHP Tutorial >How to calculate the sum of array elements using array_sum function in PHP
In PHP, array is a common data type, and the summation operation of array elements is also frequently used. PHP provides a built-in function array_sum that can easily calculate the sum of array elements. The following will introduce how to use the array_sum function to implement the sum of array elements.
First, we need to create an array containing multiple values. Suppose we have an array $numbers whose elements are [2, 4, 6, 8, 10], and we need to calculate the sum of these numbers.
PHP's array_sum function can directly sum the array elements, and the returned result is a numerical type. In this example, we can use the following code to implement array sum:
$numbers = array(2, 4, 6, 8, 10); $sum = array_sum($numbers); echo "数组元素的和为:" . $sum;
In the code, we first define an array $numbers containing multiple values, and then use the array_sum function to sum the array, And save the result in the variable $sum. Finally, use the echo function to output the result.
The output result is: the sum of the array elements is: 30
In addition to the one-dimensional array in the above example, the array_sum function can also sum multi-dimensional arrays. In multidimensional arrays, the array_sum function only sums the elements of the last dimension.
Suppose now we have a two-dimensional array $numbers whose elements are [[1, 2, 3], [4, 5, 6], [7, 8, 9]], we need to calculate these We can use the following code to realize the sum of values:
$numbers = array( array(1, 2, 3), array(4, 5, 6), array(7, 8, 9) ); $sum = array_sum(array_map('array_sum', $numbers)); echo "二维数组元素的和为:" . $sum;
In the code, we use the array_map function to save the summation result of each sub-array in a new array, and then use the array_sum function to perform the summation on the result array. Sum, and finally save the result in the variable $sum.
The output result is: the sum of the two-dimensional array elements is: 45
In addition to the usage introduced above, there are several things to note about the array_sum function:
In short, when calculating the sum of array elements, the array_sum function provided by PHP is a very convenient and practical tool, which can avoid the tedious operation of manually traversing array elements for summation.
The above is the detailed content of How to calculate the sum of array elements using array_sum function in PHP. For more information, please follow other related articles on the PHP Chinese website!