Jump to content

Archived

This topic is now archived and is closed to further replies.

a2bardeals

sum of foreach?

Recommended Posts

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:
[code]<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>[/code]

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:

[code]echo $_GET[tape1];[/code]

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:

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

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?

Share this post


Link to post
Share on other sites
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:
[code]foreach( range(1, $tapes) as $number)  {
$no = 'tape'.$number;
echo $_GET[$no];
}
[/code]

Change that to:
[code]
$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".
}
[/code]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.