Jump to content

sum of foreach?


a2bardeals

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?
Link to comment
https://forums.phpfreaks.com/topic/24895-sum-of-foreach/
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]
Link to comment
https://forums.phpfreaks.com/topic/24895-sum-of-foreach/#findComment-113454
Share on other sites

Archived

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

×
×
  • Create New...

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.