php - max winning and losing streaks (code optimization) -


i made code calculating max winning & losing streaks on array of values. can head around doing in 1 foreach loop. i'm using 2 loops follow :

  public function calculatestreaks()   {     $max_win_streak = 0;     $_win_streak = 0;     $max_loss_streak = 0;     $_loss_streak = 0;      foreach($this->all_trades_pnl $value){       if($value >= 0) {         $_win_streak++;         if($_win_streak > $max_win_streak){           $max_win_streak = $_win_streak;         }       }       else {         $_win_streak = 0;       }     }     foreach($this->all_trades_pnl $value){       if($value < 0) {         $_loss_streak++;         if($_loss_streak > $max_loss_streak) {           $max_loss_streak = $_loss_streak;         }       }       else {         $_loss_streak = 0;       }     }     return array('win_streak' => $max_win_streak, 'loss_streak' => $max_loss_streak);    }  

it works seems far optimized, ideas code better ? lot in advance, regards, john

since both loop equal think can mix them toghter , assign variables @ once follow

public function calculatestreaks() {     $max_win_streak = 0;     $_win_streak = 0;     $max_loss_streak = 0;     $_loss_streak = 0;      foreach($this->all_trades_pnl $value){       if($value >= 0) {         $_win_streak++;         if($_win_streak > $max_win_streak){           $max_win_streak = $_win_streak;         }         $_loss_streak = 0;       }       else if($value < 0) {         $_loss_streak++;         if($_loss_streak > $max_loss_streak) {           $max_loss_streak = $_loss_streak;         }         $_win_streak = 0;       }     }     return array('win_streak' => $max_win_streak, 'loss_streak' => $max_loss_streak); }  

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -