1. ## incrementally add a loop

I am trying to plot a chart and I need to loop through a SQL result.

PHP Code:
``` array( '2005' => '10', '2006' => '8', '2007' => '15', '2008' => '12' )  ```
So to plot this chart, I want to add all the previous years total to the current year in the loop so:
2005 = 10
2006 = 18 (2005 + 2006)
2007 = 33 (2005 + 2006 + 2007)
2008 = 45 (2005 + 2006 + 2007 + 2008)

2. PHP Code:
``` \$array = array('2005' => '10','2006' => '8','2007' => '15','2008' => '12');//The next line can be removed if your array is always sorted by yearksort(\$array, SORT_NUMERIC);\$sum = 0;foreach (\$array as \$year => \$value) {     \$sum += (int)\$value;     echo \$year, ' = ', \$sum, '<br>';}  ```
Edit: I beat you to it, telos!

3. Try this:
PHP Code:
``` \$array = array('2005' => '10','2006' => '8','2007' => '15','2008' => '12') ;\$total = 0;foreach(\$array as \$k => \$v){\$total += \$v;echo \$k.': '.\$total.'<br />';}  ```
Edit: You beat me to it Tarh!

4. I just figured this out too, is this a better/simpler way to do it?

PHP Code:
``` <?PHP \$data = Array(); \$data = array(     '2005' => '10',     '2006' => '8',     '2007' => '15',     '2008' => '12' ); foreach(\$data as \$y => \$n){          \$currentTotal= \$n + \$currentTotal;          echo "\$y = \$currentTotal <p>"; } ?> ```

5. Originally Posted by ripcurlksm
I just figured this out too, is this a better/simpler way to do it?
Aside from your code being very messy compared to the two samples that we posted, there's no better way to do this. It's one of the very first and most basic algorithms to be taught in almost any programming course anywhere!

6. Can I ask what makes it messy? I have accomplished with one line, what you took two lines, respectfully.

mine
\$currentTotal= \$n + \$currentTotal;
1
\$total = 0;
\$total += \$v;
2
\$sum = 0;
\$sum += (int)\$value;

7. The double declaration of \$data.

The use of a variable without having it defined first.

The lack of a sum if the array is empty.

The lack of using += shorthand.

Shorter doesn't always mean less messy.

8. Dang it, Tarh. Do you have to be so fast?

9. Thank you both for your time

10. It's a pretty good habit to initialize variables before you use them.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•