← Back to Chapters

PHP array_sum() & array_product()

? PHP array_sum() & array_product()

? Quick Overview

In PHP, the array_sum() and array_product() functions are used to calculate the sum and product of the values in an array. These functions are especially useful when working with numeric data collections.

? Key Concepts

  • array_sum() Adds all numeric values in an array
  • array_product() Multiplies all numeric values in an array
  • Works with indexed and associative arrays

? Syntax / Theory

  • array_sum(array $array): number
  • array_product(array $array): number

? Example 1: Using array_sum()

? View Code Example
// Calculate sum of numeric array values
<?php
$numbers = array(1, 2, 3, 4, 5);
$sum = array_sum($numbers);
echo $sum;
?>

? Explanation

The function adds all values in the array and returns 15.

? Example 2: Using array_product()

? View Code Example
// Calculate product of numeric array values
<?php
$numbers = array(1, 2, 3, 4, 5);
$product = array_product($numbers);
echo $product;
?>

? Explanation

The function multiplies all values and returns 120.

? Example 3: array_sum() with Associative Array

? View Code Example
// Sum values from an associative array
<?php
$prices = array("apple" => 1.2, "banana" => 0.8, "cherry" => 2.5);
$total = array_sum($prices);
echo $total;
?>

? Explanation

Only values are summed, keys are ignored. Result is 4.5.

➕ Example 4: Combining Sum and Product

? View Code Example
// Combine sum and product results
<?php
$values = array(2, 3, 4);
$sum = array_sum($values);
$product = array_product($values);
$total = $sum + $product;
echo $total;
?>

? Explanation

Sum = 9, Product = 24, Final Output = 33.

? Interactive Visualization

2 3 4

Visualizing numbers being summed or multiplied

? Use Cases

  • Total price calculation in shopping carts
  • Score aggregation systems
  • Statistical data processing

✅ Tips & Best Practices

  • Ensure array contains numeric values
  • Use validation before calculations
  • Great for financial and mathematical logic

? Try It Yourself

  • Create an array of salaries and calculate total payroll
  • Multiply quantities to find total stock value
  • Test empty arrays and observe outputs