zender Posted May 29, 2010 Share Posted May 29, 2010 Hey guys. Curious to see if I can get a little assistance with this. I'm trying to build an array within a for loop that's going to output the sum of adding consecutive numbers together. The output should look like this - [1] => 1 [2] => 3 [3] => 6 [4] => 10 and so forth, up to 100. This is what I have currently, but the only result I'm getting is Array ( [100] => 5051 ) <?php for($i=1; $i<=100; $i++) { $sum += $i; $sum_array = array( $i => $sum ); } print "<pre>"; print_r($sum_array); print "</pre>"; ?> Any suggestions would be appreciated. Link to comment https://forums.phpfreaks.com/topic/203305-sum-of-adding-consecutive-numbers-together/ Share on other sites More sharing options...
kenrbnsn Posted May 29, 2010 Share Posted May 29, 2010 You keep on redefining the $sum_array in your loop. Initialize it outside the loop and use it inside the loop: <?php $sum_array = array(); for($i=1; $i<=100; $i++) { $sum += $i; $sum_array[$i] = $sum; } echo "<pre>" . print_r($sum_array,true) . '</pre>'; ?> Ken Link to comment https://forums.phpfreaks.com/topic/203305-sum-of-adding-consecutive-numbers-together/#findComment-1065144 Share on other sites More sharing options...
ZachMEdwards Posted May 29, 2010 Share Posted May 29, 2010 [1] => 1 [2] => 3 [3] => 6 [4] => 10 Your array goes from 1 to 3 (diff of 2), 3 to 6 (diff of 3), 6 to 10 (diff of 4).<?PHP $out = array(0 => 1); $diff = 2; for($x = 1; $x <= 100; $x++) { array_push($out, $out[$x-1] + $diff); $diff++; } print_r($out); ?> Link to comment https://forums.phpfreaks.com/topic/203305-sum-of-adding-consecutive-numbers-together/#findComment-1065146 Share on other sites More sharing options...
zender Posted May 29, 2010 Author Share Posted May 29, 2010 You keep on redefining the $sum_array in your loop. Initialize it outside the loop and use it inside the loop Ken. Thanks a lot for that. I really appreciate it. I had a feeling that was the case, but I wasn't completely sure, obviously. Zach, thanks for the helping hand as well. Link to comment https://forums.phpfreaks.com/topic/203305-sum-of-adding-consecutive-numbers-together/#findComment-1065153 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.