Jump to content

Problems with foreach()


Schlo_50

Recommended Posts

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!

Link to comment
https://forums.phpfreaks.com/topic/100126-problems-with-foreach/
Share on other sites

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 />";
      }
   }
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.