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

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

Patricia Arquette
Release: 2024-11-10 05:36:02
Original
480 people have browsed it

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

Calculating Sum of Values in a Foreach Loop in PHP

In the given code snippet, you have a foreach loop that iterates through the elements of the $group array and prints the key and value of each element. However, you want to calculate the sum of the values in the $group array.

To achieve this, you can declare a variable $sum and initialize it to 0 before the foreach loop. Inside the loop, you can add the current value to the $sum variable using the = operator. After the loop, you can echo the value of $sum to display the total sum of the values in the array.

Here's the updated code:

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

This code snippet initializes $sum to 0, then iterates through the elements of the $group array. For each element, it adds the value to the $sum variable. After the loop, it echoes the value of $sum, which is the sum of all the values in the array.

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