```"/> ```">
Home > Article > Backend Development > How to sum arrays in php
In PHP, you can use the array_sum function to calculate the sum of an array. This function adds all the values in the array and returns the sum of the entire array. The following is a sample code:
<?php // 定义一个数组 $arr = array(1, 2, 3, 4, 5); // 使用 array_sum 函数计算数组的和 $sum = array_sum($arr); // 输出结果 echo "数组的和为:" . $sum; ?>
The output result is:
数组的和为:15
In the above example, we first define an array $arr, then use the array_sum function to calculate the sum of the array, and finally add the result output to the screen.
In addition to simply calculating the sum of the array, you can also implement a summation function by yourself. The following is a simple example:
<?php // 自定义函数求和 function my_sum($arr) { $sum = 0; foreach ($arr as $val) { $sum += $val; } return $sum; } // 定义一个数组 $arr = array(1, 2, 3, 4, 5); // 使用自定义函数计算数组的和 $sum = my_sum($arr); // 输出结果 echo "数组的和为:" . $sum; ?>
In this example, we define a custom function my_sum to calculate the sum of an array. In the function, we use a loop to iterate through each element in the array and accumulate it into the variable $sum, eventually returning the sum. When calling this function, pass the array $arr to the function for calculation, and finally output the calculation result to the screen.
In general, the operation of array summation in PHP is very simple and convenient. Developers only need to use the built-in function array_sum, or customize a simple summation function.
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!