Home > Backend Development > PHP Tutorial > How to Calculate the Sum of Values in a PHP Foreach Loop?

How to Calculate the Sum of Values in a PHP Foreach Loop?

Patricia Arquette
Release: 2024-11-10 12:33:02
Original
986 people have browsed it

How to Calculate the Sum of Values in a PHP Foreach Loop?

How to Sum Values in a PHP Foreach Loop

PHP foreach loops provide an efficient way to iterate over arrays and process their elements. However, if you encounter a scenario where you need to calculate the sum of values within the loop, you may be wondering how to achieve it.

To address this requirement, you can introduce a variable outside the loop to accumulate the values as you iterate through the array. Here's an example:

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

In this code, we define a variable $sum outside the loop and initialize it to 0. Then, we iterate over the $group array. For each element, we add its value to the $sum variable. Finally, after the loop, we echo the accumulated value of $sum.

By incorporating this technique, you can easily calculate the sum of values within a PHP foreach loop, allowing you to perform various calculations and aggregations based on the data in your array.

The above is the detailed content of How to Calculate the Sum of Values in a PHP Foreach Loop?. 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