tags:

views:

44

answers:

3

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.

+2  A: 

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.
Pascal MARTIN
Yes, your second example is exactly what I was trying to accomplish. This is a clear case of working on days on end and not taking a break. Thank you for your assistance.
sterling
You're welcome :-) Have fun !
Pascal MARTIN
+3  A: 

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;
Jean-Philippe
Brilliant! The problem was clearly myself, over complicating the most basic of ideas. Thank you so much for giving me a fresh and obvious perspective.
sterling
A: 

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.

just somebody