Jump to content


Photo

sum of foreach?


  • Please log in to reply
3 replies to this topic

#1 a2bardeals

a2bardeals
  • Members
  • PipPipPip
  • Advanced Member
  • 62 posts
  • LocationAnn Arbor, MI

Posted 24 October 2006 - 02:08 AM

hello.
I have 3 pages.
The point of the 3 pages is to find out the total length of multiple video tapes.

1. The first has a form with a text field that asks the customer how many video tapes they have. Which is sent via the GET method as $tapes.

2. The second page takes that number and creates the same number of select fields to find the individual lengths of the tapes.

Using:
<form name=form3 method=GET>
foreach ( range(1, $tapes) as $num ) {
echo '<select name=tape'.$num.'>';
echo '<option value=30>30 min</option>';
echo '<option value=60>60 min</option>';
echo '</select>';
}
</form>

3. The third page is the one i have problems with. I have the variable of each tape in the URL (eg. tape1=30&tape2=60) I know i can obviously manually call these values back simply by:

echo $_GET[tape1];


but i don't know how many variables will need to be added up, therfore i can't simply do that....
so i started thinking...

the variable $tapes (number of tapes) also carries over to the third page by a hidden input variable in the second page so i tried:

foreach( range(1, $tapes) as $number)  {
$no = 'tape'.$number;
echo $_GET[$no];
}

this displays the values that i need to add up....

but how do i add them up? It's probably something really obvious and my brain is too fried to think of what will do that. After 3 hours in the php.net manual still no answer.

Please will someone help me out?

#2 doni49

doni49
  • Members
  • PipPipPip
  • Advanced Member
  • 515 posts
  • LocationCentral MO

Posted 24 October 2006 - 02:17 AM

I'm assuming that the code you've already posted really does what you want and I haven't checked.

You said that the following does display all the values that you want to add up:
foreach( range(1, $tapes) as $number)  {
$no = 'tape'.$number;
echo $_GET[$no];
}

Change that to:
$total = 0;
foreach( range(1, $tapes) as $number)  {
$no = 'tape'.$number;
echo $_GET[$no];
$total += $_GET[$no];     //  <=this line basically says "take the variable 'total' and add the current number to it, changing the value of the total varialbe".
}

Don

#3 a2bardeals

a2bardeals
  • Members
  • PipPipPip
  • Advanced Member
  • 62 posts
  • LocationAnn Arbor, MI

Posted 24 October 2006 - 02:28 AM

that totally works! i made the mistake of calling the 'echo' still in the 'foreach' bracket so it was displaying every time it added a number but simply calling it after the bracket returned the sum! So thaaaaank you.

#4 doni49

doni49
  • Members
  • PipPipPip
  • Advanced Member
  • 515 posts
  • LocationCentral MO

Posted 24 October 2006 - 02:30 AM

Been there done that.  No problem.
Don




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users