php editor Xinyi today introduces you to a practical PHP skill-how to calculate the sum of all values in the returned array. In development, it is often necessary to perform a sum operation on the values in an array. Although this operation is simple, it requires certain skills. Through the introduction of this article, you will learn how to use the array_sum() function in PHP to quickly and efficiently calculate the sum of all elements in an array, making your development work more convenient and efficient. Next, let’s take a look at the specific implementation method!
There are several ways in PHP to calculate the sum of all values in an array. Here are some of the most common techniques:
1. array_sum() function
array_sum()
The function can be used to calculate the sum of all values in an array. It accepts an array as argument and returns an integer result.
<?php $numbers = [1, 2, 3, 4, 5]; $sum = array_sum($numbers); echo $sum; // Output: 15 ?>
2. Looping and accumulation
You can use loops and accumulation to manually calculate the sum of all values in an array. The following code uses foreach
to loop through each element in the array and add it to the sum:
<?php $numbers = [1, 2, 3, 4, 5]; $sum = 0; foreach ($numbers as $number) { $sum = $number; } echo $sum; // Output: 15 ?>
3. reduce() function (PHP 7 and above)
The reduce()
function was introduced in PHP 7 and above, which provides a concise and powerful way to calculate the sum of all values in an array. reduce()
The function accepts two parameters: a callback function and an initial value (optional). The callback function is applied to each element in the array, and the accumulator (initial value) stores the result of the calculation.
<?php $numbers = [1, 2, 3, 4, 5]; $sum = array_reduce($numbers, function($carry, $item) { return $carry $item; }); echo $sum; // Output: 15 ?>
4. spl_array_sum() function
SPL (Standard PHP Library) provides the spl_array_sum()
function, which is similar to the array_sum()
function, but it accepts a SplFixedArray
as argument. SplFixedArray
is a higher performance array type, often used to store large amounts of data.
<?php $numbers = new SplFixedArray([1, 2, 3, 4, 5]); $sum = spl_array_sum($numbers); echo $sum; // Output: 15 ?>
Specific data type
For specific data types, PHP also provides specialized functions to calculate their sum:
array_sum()
for integer arrayarray_sum()
For floating point arrayarray_sum()
Used for strings Arrays (add string lengths) Best Practices
array_sum()
function for general-purpose summing operations. reduce()
function or the spl_array_sum()
function for better performance. The above is the detailed content of PHP returns the sum of all values in an array. For more information, please follow other related articles on the PHP Chinese website!