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.
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!