"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Posted on 2025-02-11
Browse:102

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;

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3