Home > Article > Backend Development > How to calculate the sum of arrays in PHP
PHP is a very popular server-side programming language. It is very popular among developers for its excellent features and simple and easy-to-use syntax. Today, we will discuss how to calculate the sum of an array in PHP.
First of all, an array is a data type used to store multiple values. In PHP, an array can be one of the following types:
Next, let’s discuss how to calculate the sum of an array.
First, for indexed arrays, you can use a for loop to traverse the array and calculate the sum of all elements in the array, as shown below:
$numbers = array(1, 2, 3, 4, 5); $sum = 0; for($i = 0; $i < count($numbers); $i++) { $sum += $numbers[$i]; } echo "数组的和为:" . $sum;
The above code will output the following results:
数组的和为:15
The following is a sample code for calculating the sum of associative arrays:
$ages = array("Peter"=>32, "John"=>28, "Mary"=>21); $sum = 0; foreach($ages as $key => $value) { $sum += $value; } echo "数组的和为:" . $sum;
The above code will output the following results:
数组的和为:81
For multi-dimensional arrays, you can use recursive functions to calculate the sum of all nested arrays and, as shown below:
function sum_array($arr) { $sum = 0; foreach($arr as $element) { if(is_array($element)) { $sum += sum_array($element); } else { $sum += $element; } } return $sum; } $numbers = array(array(1, 2), array(3, array(4, 5)), array(6)); echo "数组的和为:" . sum_array($numbers);
The above code will output the following result:
数组的和为:21
To summarize, calculating the sum of an array in PHP is very simple. For indexed and associative arrays, you can use a loop to iterate over the array and calculate the sum of the elements. For multidimensional arrays, you can use a recursive function to calculate the sum of the values in all nested arrays. Hope the above content is helpful to you.
The above is the detailed content of How to calculate the sum of arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!