Jump to content

Increment a variable in a "foreach" loop


craigj1303

Recommended Posts

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:

 

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.

Link to comment
Share on other sites

It's pretty simple:

 

$i = 0;
foreach($array as $index => $value)
{
   doSomething($index, $value, $i);
   $i++;
}

 

Just replace doSomething() with your code and pseudocode variable names with your own and there you are.

Link to comment
Share on other sites

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.