zero-perfoliate
zero-perfoliate

Author Topic: Increment a variable in a "foreach" loop  (Read 165 times)

Offline craigj1303

  • New PHP Members
  • Posts: 1
  • Karma: +0/-0
Increment a variable in a "foreach" loop
« on: September 04, 2010, 02:22:35 AM »
Hi Guys

Ever had the feeling your being a spoon and can't see the wood for the trees? Well, that's how I feel today.

All I am trying to to is implement a variable in a "foreach" loop that increments by one through each iteration of the loop. I know how to do it in a "for" loop but can't for the life of me get it to work here. Here is the code:

Code: [Select]
foreach ($cart as $prodcode => $qty)
  {
    $item = get_product_details($prodcode);
    echo '<input type="hidden" name="item_name_'.[b]$needavariablehere[/b].'" value="'.$item['description'].$_SESSION['finish'][$prodcode].$_SESSION['handles'][$prodcode].'" />' . "\n";
}

Where I have highlighted $needavariablehere is where I want a number to appear i.e. if there is one item available and the foreach loop iterates once I want the number 1 here. If there are two items and the foreach loop iterates twice I want the output to have number 1 in the first line and number 2 the second time around and so on.

How many times the foreach loop iterates is based on the $cart array which contains items in a shopping cart.

Thanks for any help you can give guys.

Offline action

  • New PHP Members
  • Posts: 1
  • Karma: +0/-0
Re: Increment a variable in a "foreach" loop
« Reply #1 on: September 08, 2010, 11:20:06 AM »
try and first increment $count before your echo of the hidden input type:
aka

foreach ($cart as $prodcode => $qty)
  {
$count +=1;
    $item = get_product_details($prodcode);
    echo '<input type="hidden" name="item_name_'.$count.'" value="'.$item['description'].$_SESSION['finish'][$prodcode].$_SESSION['handles'][$prodcode].'" />' . "\n";
}