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

How to Calculate the Sum of Array Values in PHP?

Linda Hamilton
Release: 2024-11-09 13:05:02
Original
569 people have browsed it

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
];
Copy after login

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

$sum = 0;
Copy after login

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

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

Finally, the total sum can be printed:

echo $sum; // Output: 16
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template