Home > Backend Development > PHP Tutorial > How do I Sum Values Within a Foreach Loop in PHP?

How do I Sum Values Within a Foreach Loop in PHP?

Linda Hamilton
Release: 2024-11-10 04:13:03
Original
192 people have browsed it

How do I Sum Values Within a Foreach Loop in PHP?

Summing Values Within a Foreach Loop in PHP

In PHP, using a foreach loop to iterate through an array allows for the key-value pairs to be accessed. This mechanism becomes useful when requiring specific data extraction or manipulation. However, if the goal is to calculate the sum of values associated with these keys, an additional approach is needed.

Consider the following example:

foreach($group as $key => $value)
{
    echo $key . " = " . $value . "<br>";
}
Copy after login

This loop will echo the key-value pairs, resulting in an output similar to:

doc1 = 8
doc2 = 7
doc3 = 1
Copy after login

To sum the values associated with these keys, a separate variable must be initialized to accumulate these values:

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

In this example, the $sum variable is initialized to 0 and incremented by the value associated with each key during each iteration. After the loop completes, $sum contains the summation of all values, which can then be echoed to display the result, in this case, 16.

This approach allows for the efficient summation of values within a foreach loop, making it convenient for various data analysis or calculation tasks.

The above is the detailed content of How do I Sum Values Within 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