CodeIgniter Forums

Full Version: Can you build an array with a for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]ppwalks[/eluser]
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

El Forum

[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

El Forum

[eluser]ppwalks[/eluser]
Superb Pal, thanks a bunch..