Re: Looping Addition

From: Date: Thu, 05 Dec 2002 19:51:18 +0000
Subject: Re: Looping Addition
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-127192@lists.php.net to get a copy of this message
You simply need the absolute value of the difference. So taking Stephen's example below.. $total = 0; foreach( $_POST['nums'] as $number ) { $total -= $number; // if users inputs 5 as first value result equals -5 $total = abs($total); // result now equals 5 } ----- Original Message ----- From: "Stephen" <webmaster@melchior.us> To: "Chris Wesley" <cwwesley@udlug.org> Cc: "PHP List" <php-general@lists.php.net> Sent: Thursday, December 05, 2002 12:33 PM Subject: Re: [PHP] Looping Addition > Continuing this even more...how would I use this same method only to > subtract? > > What I'm doing right now would result in the following sitution. > > The user types in 5 as their first number. The second number is 4. Instead > of returnin 1, it returns -9. It's subtracting the first number from 0, then > taking 4 and subtracting that from -5. How can I fix this keeping in mind > the user may type in more then two numbers? > > > ----- Original Message ----- > From: "Chris Wesley" <cwwesley@udlug.org> > To: "PHP List" <php-general@lists.php.net> > Cc: "Stephen" <webmaster@melchior.us> > Sent: Wednesday, December 04, 2002 8:42 PM > Subject: Re: [PHP] Looping Addition > > > > On Wed, 4 Dec 2002, Stephen wrote: > > > This is only a snippet, there is more to it but for simplicities sake... > > > Then I calculate it. My question is, how would I loop the adding? I hope > you > > > understand this now... > > > > Ah!, I think I understand better now. You want to add num1, num2, num3, > > ... numN, which are inputs from the second form in your sequence. Gotcha. > > > > If you name /all/ the form elements as "nums[]" instead of individually as > > "num${current}", the numbers put into the form will all be accessible in > > one array to the PHP script that does the adding. Then you can just loop > > over the array of numbers. > > > > In your second form, change this: > > "<input name="num<?php echo $current; ?>" type="text" > > id="vars" value="0" > > size="25">" > > > > To this: > > "<input name="nums[]" type="text" id="vars" > > value="0" size="25"> > > > > Then in the script that adds the numbers: > > $total = 0; > > foreach( $_POST['nums'] as $number ){ > > $total += $number; > > } > > > > Hopefully I understood your problem this time! Let me know if I missed > > again. > > g.luck, > > ~Chris > > > > > > > -- > PHP General Mailing List (http://www.php.net/) > To unsubscribe, visit: http://www.php.net/unsub.php > >

« previous php.general (#127192) next »