简体   繁体   中英

PHP Calculation, break point, and reset value in foreach loop

How do you calculate (sum) + a value in foreach loop?

I am working on a cricket application where i have to count the loop for each 6 times and then count specific value and then echo the total.

I have a code not exact but something like this.

And there are two values:

  1. Balls $balls['1']; array like 1,2,3,4,5 and up to 300-1000 balls
  2. Runs $balls['6']; array like 2,3,1,5 random numbers could be any;
  3. Values comes from mysql table columns balls and runs
foreach( $balls as $ball ){
    $countball++;
    // here is what i need to know how do i calculate the values of $ball + $ball?
    // so i can echo it inside the below if condition?
    $runs = $ball['runs'] + $ball['runs']; // not working
    if($countball == 6){
        echo $runs;
    }
    $runs+= $ball; // reset the ball counting to continue addition from loop?
    // and reset the
}// end foreach

however something like this works fine for the first $countball == 6. but after that it does not show the exact value

You forget to reset the $countball.

You may change the if part as :

if($countball == 6)
{ 
    echo $runs;
    $countball = 0; 
}

Maybe this is what you need:

$runs = 0;
foreach( $balls as $ball ){
    $runs += $ball['runs'];
}
echo $runs;

With help of @Barmar from above i got the desired output as followings

      $runs = 0;
        $countball=0;
        foreach( $balls as $ball ){
            $countball++;
            $runs += $ball['runs'];
            if($countball == 6){
//  reset runs from current loop runs for next, if i reset $runs = 0
//  for some reason it does not (SUM) + this loops $ball['runs'] with last 5;
            $runs = $ball['runs']; 
            $countball=0;
            }// end if $countball == 6
        }// end foreach
            echo $runs;

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