craigj1303 Posted September 4, 2010 Share Posted September 4, 2010 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 https://forums.phpfreaks.com/topic/212504-increment-a-variable-in-a-foreach-loop/ Share on other sites More sharing options...
Zyx Posted September 4, 2010 Share Posted September 4, 2010 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 https://forums.phpfreaks.com/topic/212504-increment-a-variable-in-a-foreach-loop/#findComment-1107136 Share on other sites More sharing options...
craigj1303 Posted September 5, 2010 Author Share Posted September 5, 2010 Superb, thanks so much Link to comment https://forums.phpfreaks.com/topic/212504-increment-a-variable-in-a-foreach-loop/#findComment-1107591 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.