$arr = [ 1 , 2 , -4 , 4 , 10 , -23 , 4 , -5 , 1]; $max_sum = 0; $sum=0; $new = []; $i = 1; echo '<pre/>'; foreach( $arr as $key => $value ){ if($sum<0){ unset($new[$i]); $i++; $sum=$value; }else{ $sum+=$value; } $new[$i][] = $value; if($max_sum<$sum){ $max_arr = $new; $max_sum=$sum; } } print_r($max_sum); print_r($max_arr); exit;