In PHP, it is very convenient to perform sum operations on arrays. Below we will introduce the summing method of PHP arrays in detail.
1. Use array_sum function to sum
PHP’s built-in array_sum function can sum all the values in the array. Its syntax format is as follows:
array_sum(array $array): float
Among them, $array represents the array to be summed, and the return value is the summation result. It should be noted that array_sum can only sum elements whose values are numbers. If there are non-numeric elements in the array, 0 will be returned.
The following is an example that demonstrates how to use the array_sum function to sum an array:
$numbers = array(1, 2, 3, 4, 5); $total = array_sum($numbers); echo "数组的和为:$total";
The running result is:
数组的和为:15
2. Use foreach loop summation
In addition to using PHP's built-in array_sum function, we can also use the foreach loop to accumulate the values in the array one by one. The specific method is:
The following is an example that demonstrates how to use a foreach loop to sum an array:
$numbers = array(1, 2, 3, 4, 5); $total = 0; foreach ($numbers as $number) { $total += $number; } echo "数组的和为:$total";
The running result is:
数组的和为:15
3. Use a while loop to sum
In addition to using the foreach loop, we can also use the while loop to sum the array. The specific method is:
The following is an example that demonstrates how to use a while loop to sum an array:
$numbers = array(1, 2, 3, 4, 5); $total = 0; $index = 0; while ($index < count($numbers)) { $total += $numbers[$index]; $index++; } echo "数组的和为:$total";
The running result is:
数组的和为:15
4. Use recursive functions to sum
Finally, we can also use recursive functions to sum multi-dimensional arrays. The specific method is:
The following is an example that demonstrates how to use a recursive function to sum multi-dimensional arrays:
function array_sum_recursive($array) { $total = 0; foreach ($array as $element) { if (is_array($element)) { $total += array_sum_recursive($element); } else { $total += $element; } } return $total; } $numbers = array(1, 2, array(3, 4), 5); $total = array_sum_recursive($numbers); echo "数组的和为:$total";
The running result is:
数组的和为:15
The above is the PHP array sum There are several methods. You can choose the appropriate method to implement the array summation function according to your actual needs.
The above is the detailed content of How to sum arrays in php. For more information, please follow other related articles on the PHP Chinese website!