Hi,
i've a form that submits fields with dynamically generated names. eg. quantity1, quantity2 etc, depending on the number of items being submitted. i need to calculate the total quantity which will be the sum of the values submitted in all of these fields. i'm very new to php (in fact to programming in general - so for all I know I'm going about it totally wrong) but what I've got so far is the following code:
for ($a=1; $a<=$calculate; $a++){
$b = "quantity".$a;
$c = $$b;
}
where $calculate is the number of fields. What i need is to be able to add up all the values of $c

hope someone can help
thanks

    u need to create a loop with a counter #i, then loop through the array

    loop $i to whatever
    $total = $total + array;

    that should do the job.

    home time, ciao.

      As bernouli pointed out, your original error was using '=' instead of '+=', but just for grins I will post yet another way to do it....

      for ($a=1; $a<=$calculate; $a++){
         $total += ${'quantity'.$a};
      }
      

      By the way, in PHP you will find it more common to name such variables with square brackets (i.e. quantity[]) which PHP will accept as an array. Your approach, using variable variables, is a bit more work but happens to be the method that usually appeals to me. Not sure why, probably because brackets don't seem to belong inside forms. They look funny to me as input names and I just don't trust them 😃

      In the case of check boxes, though, giving each checkbox a different name is not too elegant a solution either. In that case I usually use the array method.

        thanks guys
        i knew it would turn out to be something ridiculously simple like that - what's painfully obvious to you is not obvious at all to me. anyway, the whole thing works perfectly now. thanks again

          Write a Reply...