How to Use array_sum and array_product in PHP

In PHP, processing arrays of numbers is a common task, and the built-in functions array_sum() and array_product() offer quick, efficient ways to perform calculations. This article explains the distinct purposes of these two mathematical functions, provides clear code examples of how they work, and highlights how they simplify array manipulation without the need for manual loops.

The array_sum() Function

The array_sum() function calculates and returns the sum of all the values in an array. It takes a single array as its argument and traverses through all its elements, adding them together.

Syntax

array_sum(array $array): int|float

Key Behaviors

Example

$integers = [5, 10, 15, 20];
echo array_sum($integers); // Outputs: 50

$floats = [1.5, 2.5, 3.0];
echo array_sum($floats); // Outputs: 7

The array_product() Function

The array_product() function calculates and returns the product of all the values in an array. It multiplies every numerical element in the array by one another.

Syntax

array_product(array $array): int|float

Key Behaviors

Example

$numbers = [2, 3, 4];
echo array_product($numbers); // Outputs: 24 (2 * 3 * 4)

$emptyArray = [];
echo array_product($emptyArray); // Outputs: 1

Summary of Differences

Feature array_sum() array_product()
Mathematical Operation Addition (\(x + y + z\)) Multiplication (\(x \times y \times z\))
Return value for empty array 0 1
Common Use Case Calculating shopping cart totals, test score averages, or financial tallies. Calculating probabilities, geometric growth, or dimensional volumes.