Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_sum() and array_product() functions

Reference for PHP array_sum() and array_product(): add or multiply all values of an array, int versus float results, empty arrays and PHP 8.3 warnings.

array_sum() adds up all values in an array, and array_product() multiplies them. Both return an int when every value is an integer and a float as soon as a float takes part. Numeric strings such as "4" are converted.

The two functions are the quickest way to total a list of prices or to compute a factorial-like product. For anything more complex, such as summing one field of each row, combine them with array_column() or array_map().

PHP
<?php
echo array_sum([1, 2, 3]);      // 6
echo array_product([2, 3, 4]);  // 24

Try it

PHP Totals and products

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Summing a field and an average

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_sum(array $array): int|float
array_product(array $array): int|float
Name Description
$array The array of values to add or multiply.

Return value: the sum or product. array_sum([]) is 0 and array_product([]) is 1, both integers.

Usage notes

  • Type of the result: if all values are integers the result is an int; one float anywhere makes it a float. If an integer sum overflows, PHP switches to float.
  • Floating-point error: 0.1 + 0.2 is not exactly 0.3. Round when you display money, or work in cents with integers.
  • Conversions: numeric strings are converted, booleans become 1 and 0, and null becomes 0.
  • Unsupported values (PHP 8.3+): arrays and objects are skipped with a warning. Before PHP 8.3 arrays were skipped silently. Do not rely on this; clean the data first.
  • Empty product is 1: array_product([]) returns 1, the neutral element of multiplication, not 0. Check for an empty array first if that matters to you.
  • Keys are ignored. Only the values take part.
  • Averages: divide by count(), and guard against an empty array to avoid a DivisionByZeroError.