Backend Development 4 min read

Using PHP's array_sum() Function to Sum Array Elements

This article explains PHP's built-in array_sum() function, demonstrating how to calculate the sum of numeric arrays and associative arrays, shows performance benefits, and provides examples combining it with array_map() for more complex calculations.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's array_sum() Function to Sum Array Elements

array_sum() is a built‑in PHP function that returns the sum of all values in an array passed as its argument.

How to use array_sum()

Below is a simple example that calculates the sum of a numeric array:

<code>$numbers = array(1, 2, 3, 4, 5);
$sum = array_sum($numbers);
echo "数组 $numbers 的总和是:$sum";</code>

In this code, an array $numbers containing five integers is defined, then array_sum() computes the total, and the result is printed.

array_sum() can also be used with associative arrays; only numeric values are summed while string values are ignored. Example:

<code>$prices = array('apple' => 0.99, 'banana' => 1.25, 'orange' => 0.75);
$total = array_sum($prices);
echo "最终总价是:$total";</code>

Here, $prices is an associative array mapping fruit names to prices, and array_sum() returns the total price.

Advantages of array_sum()

Using array_sum() allows rapid and convenient summation of all elements in an array of any size and type, eliminating the need to write explicit loops, which makes code shorter and easier to maintain. Its performance is also strong for large data sets.

Beyond simple summation, array_sum() can be combined with other functions for more complex tasks. For instance, using array_map() to add corresponding elements of two arrays and then summing the results:

<code>$numbers1 = array(1, 2, 3, 4, 5);
$numbers2 = array(6, 7, 8, 9, 10);

$sums = array_map(function($x, $y) {
    return $x + $y;
}, $numbers1, $numbers2);

$total = array_sum($sums);

echo "两个数组中元素之和的总和是:$total";</code>

This code defines two numeric arrays, uses array_map() to create a new array $sums containing the element‑wise sums, then applies array_sum() to obtain the total of all summed values.

Overall, array_sum() is a highly useful built‑in function that quickly computes the sum of array elements, works with arrays of any size, improves code readability, and can be combined with other functions to handle more advanced calculations, thereby boosting development efficiency.

Backendphp-functionsarray-manipulationarray_sum
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.