Jump to content

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


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;

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.