Reputation: 625
How can I write this in such a way that $counter value is 1 on its first iteration and 0 on each following cycle?
$counter =1;
foreach($result):
$number = $result['value'] + $counter;
db->update($result['value'] => $number);
$counter--;
endforeach;
Essentially my goal is to get $number to be $number+1 on the first loop and then $number+0 for each following loop.
The value of $result['value'] will be set after the first loop to $number+1, so on the next cycle $result['value'] will be the needed unchanged value.
Upvotes: 0
Views: 279
Reputation: 19247
the code looks like PHP although it is not syntactically valid. I'll assume the iterated variable (here called $results
) has numeric keys starting at 0:
foreach($results as $counter => $result):
$number = $result['value'] + !$counter;
notice the negation.
Upvotes: 0
Reputation: 756
I do not see where the problem resides.
$counter = 1;
foreach($result):
$number = $result['value'] + $counter;
// Once you have used your variable, just set it to zero...
$counter = 0;
db->update($result['value'] => $number);
endforeach;
Upvotes: 3
Reputation: 400932
Why not just use something like this :
$counter
is 1
0
Which would give you some code that would look like this :
$counter = 1;
foreach($result):
$number = $result['value'] + $counter;
db->update($result['value'] => $number);
if ($counter == 1) {
$counter = 0;
}
endforeach;
Or, you could also just set $counter
to 0
at the end of the loop, not testing anything :
$counter = 1;
foreach($result):
$number = $result['value'] + $counter;
db->update($result['value'] => $number);
$counter = 0;
endforeach;
With this :
$counter
would be 1
, as initialized before the loop0
0
after each iteration -- i.e. it would stay at 0
.Upvotes: 2