t_machine Posted September 28, 2007 Share Posted September 28, 2007 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 Link to comment https://forums.phpfreaks.com/topic/71072-solved-is-it-possibe-to-sum-values-while-in-loop/ Share on other sites More sharing options...
wildteen88 Posted September 28, 2007 Share Posted September 28, 2007 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; Link to comment https://forums.phpfreaks.com/topic/71072-solved-is-it-possibe-to-sum-values-while-in-loop/#findComment-357347 Share on other sites More sharing options...
rarebit Posted September 28, 2007 Share Posted September 28, 2007 yep, that's what I was gonna say... Link to comment https://forums.phpfreaks.com/topic/71072-solved-is-it-possibe-to-sum-values-while-in-loop/#findComment-357348 Share on other sites More sharing options...
t_machine Posted September 28, 2007 Author Share Posted September 28, 2007 Thanks very much. Works great Link to comment https://forums.phpfreaks.com/topic/71072-solved-is-it-possibe-to-sum-values-while-in-loop/#findComment-357351 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.