Schlo_50 Posted April 8, 2008 Share Posted April 8, 2008 I have some fields representing quantity that are displayed on a page with unique values. The unique values assigned to the fields are the names of the items stored in my database. I am trying to run a foreach() loop so that later I can print out the unique values against the quantities typed in the fields. E.g. Item | Quantity item1| 3 item2| 5 item3| 3 The trouble is, where the string 'Item' should say the item name, it infact says the item number. Hence: Item | Quantity 21 | 3 45 | 5 98 | 3 This is my script to generate the fields: <?php print " <input name=\"quantity[{$productid}]\" type=\"text\" size=\"3\" maxlength=\"3\" class=\"main\" onfocus=\"this.style.border='1px dashed #fe9b1b'\" onblur=\"this.style.border='1px solid #a5acb2'\"/> <input name=\"orderid[{$productid}]\" value=\"{$productid}\" type=\"hidden\"/> <input name=\"quanname[{$productname}]\" type=\"hidden\"/> "; ?> And this is the script to try out the loop: $qua = $_POST['quantity']; $nam = $_POST['quanname']; foreach($qua as $a => $nam){ if($nam>0){ print "$a - $nam<br />"; } } Anyone got any ideas? Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/100126-problems-with-foreach/ Share on other sites More sharing options...
cooldude832 Posted April 8, 2008 Share Posted April 8, 2008 it has nothing to do with foreach its cause you are using the productid as the array key which i'll assume is an integer and not a string thus you have the issue you say. use what you want php can't predict it for you. Quote Link to comment https://forums.phpfreaks.com/topic/100126-problems-with-foreach/#findComment-511925 Share on other sites More sharing options...
KevinM1 Posted April 8, 2008 Share Posted April 8, 2008 More to the point, the following makes no sense: $qua = $_POST['quantity']; $nam = $_POST['quanname']; foreach($qua as $a => $nam){ if($nam>0){ print "$a - $nam<br />"; } } Anyone got any ideas? Thanks! You can't plug in an outside value for use in a foreach-loop. So, either your $a or $nam value isn't what you're hoping it to be. In other words: <?php $qua = $_POST['quantity']; $nam = $_POST['quanname']; foreach($qua as $a => $nam){ /* $a is the key which, in this case, is the number specifying the current value's position in the array $qua[]. $nam is ACTUALLY $qua[$a] here, not $nam[$a], as you're overwriting $nam with each iteration of the loop. */ } ?> Instead of foreach, try a for-loop: <?php for($i = 0; (($i < count($qua)) && ($i < count($nam)); $i++{ //the conditional assumes that $qua and $nam have the same number of values if($nam[$i] > 0){ echo "{$qua[$i]} -- {$nam[$i]}<br />"; } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/100126-problems-with-foreach/#findComment-511940 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.