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|floatKey Behaviors
- Return Type: It returns the sum as an integer or a float, depending on the values inside the array.
- Empty Arrays: If the input array is empty, the
function returns
0. - Non-Numeric Values: If the array contains strings
or other non-numeric types, PHP will attempt to cast them to numbers.
Non-numeric strings that cannot be cast are treated as
0.
Example
$integers = [5, 10, 15, 20];
echo array_sum($integers); // Outputs: 50
$floats = [1.5, 2.5, 3.0];
echo array_sum($floats); // Outputs: 7The 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|floatKey Behaviors
- Return Type: It returns the product as an integer or a float.
- Empty Arrays: If the input array is empty, the
function returns
1. This is because 1 is the multiplicative identity. - Non-Numeric Values: Similar to
array_sum(), PHP will attempt to cast non-numeric values. However, if a value evaluates to0(such as a non-numeric string), the entire product will become0.
Example
$numbers = [2, 3, 4];
echo array_product($numbers); // Outputs: 24 (2 * 3 * 4)
$emptyArray = [];
echo array_product($emptyArray); // Outputs: 1Summary 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. |