I have: <input type="text" name="qty'.$i.'"> I have a few instances of this field. How can I add the value of all of them?
<?php if (isset($_POST['submit'])){ $qtyLength = 0 ; $qtySum = 0 ; //calculate number of input elements with qty in their name foreach ($_POST as $key => $post) { if (stristr($key, 'qty')){ $qtyLength++ ; } } //Calculate sum for($i = 1; $i <= $qtyLength ; $i++ ){ $qtySum += $_POST['qty'.$i] ; } echo 'Sum is ' .$qtySum ; } ?> PHP: <form method="post" action=""> <input type="text" name="qty1" /> <input type="text" name="qty2" /> <input type="text" name="qty3" /> <input type="submit" value="submit" name="submit"> </form> HTML: Ofcourse validation is missing , but it works HTH
I would like to add that a few things are missing from the above code. Like the check if $_POST['qty'.$i] isset before attempting to read it. etc.
I would suggest changing this: <input type="text" name="qty'.$i.'"> To this: <input type="text" name="qty['.$i.']"> Then you could just do $total = array_sum($_POST['qty']); Since $_POST['qty'] would then be an ARRAY. So to rework kutchbhi's example: <form method="post" action=""> <input type="text" name="qty[0]" /> <input type="text" name="qty[1]" /> <input type="text" name="qty[2]" /> <input type="submit" value="submit" name="submit"> </form> Code (markup): <?php if ( isset($_POST['qty']) && is_array($_POST['qty']) ) { echo 'Sum is ',array_sum($_POST['qty']),'<br />'; } else { echo 'Unable to create sum, [QTY] either nonexistant or not an array!<br />'; } ?> Code (markup): A lot simpler, no? One of the big tricks to getting really good at PHP is to realize that in a LOT of cases there already are functions or object methods of handling most anything you can think of... That's why PHP is best used as glue between markup, it's function library, and external engines like SQL -- it blows chunks as a general computing language, so don't "Brute force code" anything you don't have to. Though as kutchbhi said, you might want to do some validation first... though I added some simple/primitive checking.