简体   繁体   中英

Get a total of field values in foreach loop

So my code is

if ($activities) {
      foreach ($activities as $activity) {
        $price = $activity['price'];
        if($price) {echo $price;};
      }
    }

and i would like to add the values of the $price field to get a grand total to echo

The real work goes on in this line, which increments the total every time the loop iterates (comes around): $total += $price;

$total = 0;
if ($activities) {
  foreach ($activities as $activity) {
    $price = $activity['price'];
    if($price) {
        echo $price; // do you still need this?
        $total += $price;
    }
  }
}
echo $total;

Why use a loop? I would use array_sum() .

$total = array_sum(array_filter(array_values($activities)));

array_values returns all the values. array_filter filters out anything that evaluates to false (like null or 0). array_sum adds them up.

Functional programming is your friend. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM