Jump to content


Photo

'WHILE' help


  • Please log in to reply
3 replies to this topic

#1 embsupafly

embsupafly
  • Members
  • PipPip
  • Member
  • 29 posts

Posted 07 April 2006 - 11:06 PM

I have 10 sets of session vars, pr_(1-10) and q_(1-10), where pr is price and q is quantity.

I need to multiply each pr with its corresponding q (pr_1 * q_1) and add these all together, I thought a while loop would help, but I think I have the syntax wrong. Listed below is the snippet, I think I am just missing a little piece of the puzzle, I should step away and come back to it, but in the meantime, any help would be appreciated.

$i = 1;
while ($i <= 10) {
$wo_parts_total = ($_SESSION['pr_$i'] * $_SESSION['q_$i']) +;
$i++;
}

Eric

#2 Yesideez

Yesideez
  • Members
  • PipPipPip
  • Advanced Member
  • 2,334 posts
  • LocationDevon, UK

Posted 07 April 2006 - 11:16 PM

I think you'll find a for() loop more appropriate here especially seeing that you're only using the range 1-10.

$wo_parts_total=0;
for ($i=1;$i<=10;$i++) {
  $pr="pr_$i";
  $q="q_$i";
  $wo_parts_total+=($_SESSION[$pr]*$_SESSION[$q]);
}
Enclosing variables in single quotes won't give you the values of the variables but will instead use that string exactly as shown - surrounding variables in double quotes will insert their contents.
Not a pro just an enthusiast :)

if (empty($coffee)) {$coffee=new coffee();}

Please surround any code using the CODE tags - I rarely look at anything without them

#3 embsupafly

embsupafly
  • Members
  • PipPip
  • Member
  • 29 posts

Posted 07 April 2006 - 11:23 PM

Cool just what I was looking for.
Eric

#4 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 08 April 2006 - 12:01 AM

You could have saved yourself a lot of code if you had made $pr and $q arrays, then you would have been able to do:
<?php
$pr = $_SESSION['pr'];
$q = $_SESSION['q'];
for ($i=1;$i<=10;$i++)
   $wo_parts_total += $pr[$i] * $q[$i];
?>

Ken




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users