Home  >  Article  >  Backend Development  >  How to Calculate the Sum of Array Values in PHP?

How to Calculate the Sum of Array Values in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-09 13:05:02537browse

How to Calculate the Sum of Array Values in PHP?

Assigning and Summing Array Values in a Loop

Consider an array with key-value pairs, such as:

$group = [
    'doc1' => 8,
    'doc2' => 7,
    'doc3' => 1
];

To obtain the sum of the values, an initialization step is necessary:

$sum = 0;

With this initialized variable, a loop can accumulate the values as follows:

foreach ($group as $key => $value) {
  $sum += $value;
}

Finally, the total sum can be printed:

echo $sum; // Output: 16

This solution efficiently calculates the sum of array values by iteratively adding them to a running total.

The above is the detailed content of How to Calculate the Sum of Array Values in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn