Page 1 of 1

using loops to shorten code

Posted: Wed Nov 10, 2010 1:06 pm
by Obadiah
say in trying to get the sum of 68 numbers

instead of doing

Code: Select all

$sum_of = $num1+$num2+$num3//till $num68
how can i use a loop to shorten it?...or can i?

Re: using loops to shorten code

Posted: Wed Nov 10, 2010 1:20 pm
by McInfo
Where do the $num variables come from? I would expect that many related values to be in an array rather than individual variables.

Re: using loops to shorten code

Posted: Wed Nov 10, 2010 1:37 pm
by Obadiah
they are from an array...i take the numbers from the database and i want to add them up

Re: using loops to shorten code

Posted: Wed Nov 10, 2010 1:45 pm
by McInfo
Why not calculate the sum in the SQL query?

Code: Select all

SELECT SUM(`x`) ...
If that doesn't work, try array_sum().

Re: using loops to shorten code

Posted: Wed Nov 10, 2010 1:46 pm
by VladSun
I f these are columns, how about using http://www.php.net/manual/en/function.array-sum.php ?

Re: using loops to shorten code

Posted: Wed Nov 10, 2010 2:25 pm
by Obadiah
because user1 will enter 23 for question 1
and user2 will enter 67 for question 1

the answers to the same question are stored on different rows

Re: using loops to shorten code

Posted: Wed Nov 10, 2010 2:28 pm
by VladSun
So, SUM them in SQL as McInfo suggested :)