How to move a step back in foreach loop?
How do i move a step back in a foreach loop? Say i have something like this:
Do something for the first run. If b == 1, do something again. See code below.
$i = 0; foreach ($a as $b) { if ($i == 0) { //something } 开发者_运维技巧 if ($b == '1') { $i = 0; } $i++; }
The problem is, when $b == 1, it is setting $i = 0 but not running the instructions inside. Any better way to overcome this if it's not possible to step back?
Update: Thanks guys for the response. Sorry i wan't clear when i typed this.
But I'd managed to achieve what i want by putting the loop in a function and do some conditional checks and pass arguments before calling it.
Not sure if this is a typo, but you have if ($i = 0) instead of if ($i == 0). Possibly your problem is there?
Perhaps another option would be just doing:
if ($b == '1') {
// do something?
}
Final option would be to do a regular for loop and decrement the counter if a condition exists:
for ($x = 0; $x < count($thing); $x++) {
if($thing[$x] == '1') {
$x -= 1;
}
}
are you sure that $i is getting set to 0 in the loop, it is quite possible it is always 0 (because that is what it is set to before the loop)
精彩评论