sterling
sterling

Reputation: 625

Limit counter value after first loop cycle

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

Answers (3)

just somebody
just somebody

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

Caissy
Caissy

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

Pascal MARTIN
Pascal MARTIN

Reputation: 400932

Why not just use something like this :

  • test if $counter is 1
  • is yes, set it to 0
  • else, do nothing

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 :

  • The first time you are in the loop, $counter would be 1, as initialized before the loop
  • At the end of the first iteration, it would be set to 0
  • And it would then re-set to 0 after each iteration -- i.e. it would stay at 0.

Upvotes: 2

Related Questions