Welcome Guest, Not a member yet? Register   Sign In
Can you build an array with a for loop
#2

[eluser]TWP Marketing[/eluser]
[quote author="ppwalks" date="1344447239"]I am trying to build an array to insert into db, I have a count and want to build the array according to the count so used a for loop, except it is only showing the last result of the array so could someone help with this please.

Code:
$count = count($_POST['cat_id']);

for ($i=1; $i<=$count; $i++)
  {
  $product = array( $i => $prod);
  }

The ouput to screen is:

( [7] => 126 )

when it should start from 1 and increment to 7 as a for loop should, where am i going wrong[/quote]

You are overwriting the array on each loop.
Try this:
Code:
$count = count($_POST['cat_id']);
$product = array(); // define the array first
for ($i=1; $i<=$count; $i++)
  {
  $product[$i] = $prod; //assign a value to the element $i in array $product
  }
NOTE the value of $prod is not set, so it will always be undefined unless you set it outside the loop
Also your counter $i starts at 1, while an array index can/should start at zero


Messages In This Thread
Can you build an array with a for loop - by El Forum - 08-08-2012, 10:33 AM
Can you build an array with a for loop - by El Forum - 08-08-2012, 10:54 AM
Can you build an array with a for loop - by El Forum - 08-08-2012, 11:01 AM



Theme © iAndrew 2016 - Forum software by © MyBB