You are here: Re: help with adding « PHP « IT news, forums, messages
Re: help with adding

Posted by Jamie Alessio on 10/01/78 11:09

> I have messed with this for a couple of days and cant get it right. Maybe I
> need sleep :-)
>
> The code below is echoing the qty correctly (10, 5, 25)
>
> for ($i = 1; $i <= $sendnum; $i++)
>
> {
>
> $qty = $_POST['qty'.$i];
>
> echo $qty . '<br />';
>
> }
>
> The question is, how would I take add each of these numbers (10+5+25)?
>
Jay,
Maybe I'm missing something here but wouldn't this do the trick?

///////////////
$total = 0;
for ($i = 1; $i <= $sendnum; $i++)
{
$qty = $_POST['qty'.$i];
echo $qty . '<br />';
$total += $qty;
}
echo "Total = {$total}<br>";
///////////////

I have a suggestion related to how you are naming elements in your form.
Based on the way you are accessing elements in your $_POST array it
looks like your form is setup something like this:

<input name="qty1">
<input name="qty2">
....
<input name="qty99">

The problem is that when the form is posted you have no way to easily
loop over all the "qty" elements. In your example you are using a for()
loop with $sendnum which is a value you had to figure out one way or
another. An easier solution might be to do something like this:

<input name="qty[1]">
<input name="qty[2]">
...
<input name="qty[99]">

and then in your PHP code you can easily loop over the values like this:

///////////////
$total = 0;
foreach($_POST['qty'] as $key => $value)
{
echo "The quantity for {$key} is {$value}<br>";
$total += $value;
}
echo "Total = {$total}<br>";
///////////////

Actually, now that all your values are now in an array you could remove
the $total calculation from the loop and calculate it by doing this:

$total = array_sum($_POST['qty']);

Try using arrays in your forms instead of sticking numbers onto the end
of your variable names and I think you'll find things getting much
easier for you.

- Jamie

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация