"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 Array Values in PHP?

How to Calculate the Sum of Array Values in PHP?

Published on 2024-11-13
Browse:969

How to Calculate the Sum of Array Values in PHP?

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.

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