Assigning and Summing Array Values in a Loop
Consider an array with key-value pairs, such as:
$group = [ 'doc1' => 8, 'doc2' => 7, 'doc3' => 1 ];
To obtain the sum of the values, an initialization step is necessary:
$sum = 0;
With this initialized variable, a loop can accumulate the values as follows:
foreach ($group as $key => $value) { $sum += $value; }
Finally, the total sum can be printed:
echo $sum; // Output: 16
This solution efficiently calculates the sum of array values by iteratively adding them to a running total.
The above is the detailed content of How to Calculate the Sum of Array Values in PHP?. For more information, please follow other related articles on the PHP Chinese website!