using loops to shorten code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Obadiah
Forum Regular
Posts: 580
Joined: Mon Jul 31, 2006 9:13 am
Location: Ashland, KY
Contact:

using loops to shorten code

Post 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?
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: using loops to shorten code

Post 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.
User avatar
Obadiah
Forum Regular
Posts: 580
Joined: Mon Jul 31, 2006 9:13 am
Location: Ashland, KY
Contact:

Re: using loops to shorten code

Post by Obadiah »

they are from an array...i take the numbers from the database and i want to add them up
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: using loops to shorten code

Post 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().
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: using loops to shorten code

Post by VladSun »

I f these are columns, how about using http://www.php.net/manual/en/function.array-sum.php ?
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
Obadiah
Forum Regular
Posts: 580
Joined: Mon Jul 31, 2006 9:13 am
Location: Ashland, KY
Contact:

Re: using loops to shorten code

Post 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
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: using loops to shorten code

Post by VladSun »

So, SUM them in SQL as McInfo suggested :)
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply