Jump to content

[SOLVED] Is it possibe to sum values while in loop?


t_machine

Recommended Posts

I am wondering if anyone could help with this problem

I would like to know if it's possible to add values while using a foreach loop. In the array below I have values lesser and greater than 10. I was wondering if during the loop I can check if the value is higer than 10 and basically sum all the values greater than 10.

 

Example:

$myarray = array(12, 6, 25, 2, 1, 15, 20);

 

foreach($myarray as $val){

 

if($val >10){

//STARTING ADDING TO THE NEXT VALUE THAT IS GREATER THAN 10

}

 

}

 

 

Thanks for any help :)

Yes you can do that, your example is correct:

$myarray = array(12, 6, 25, 2, 1, 15, 20);

$gt10_total = 0;
foreach($myarray as $val)
{
    if($val >10)
    {
         $gt10_total += $val;
    }
}

echo 'Total (greater than 10): ' . $gt10_total;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.