Calling all coders. Moving around a counter ??

Permabanned
Joined
13 Nov 2006
Posts
5,798
In php I have a count that goes 0,1,2 then goes back to 0.

If the count was on 1 how would i make it go back two places so that it would end up on 2 ??

any ideas.
 
Last edited:
High level approach, as I am not that up with PHP, create a counter object, that has a plus and minus method and do all the wrapping of the counter in that

From memory PHP is OOP to a certain extend right? Otherwise the code is going to be quite messy.
 
High level approach, as I am not that up with PHP, create a counter object, that has a plus and minus method and do all the wrapping of the counter in that

From memory PHP is OOP to a certain extend right? Otherwise the code is going to be quite messy.

What :/

You just need to use modular arithmetic, specifically the % (modulus) operator:

Code:
$counter = ($counter + $increment) % 3;

Edit: this is more robust:

Code:
$counter = ($counter + $increment + ceil(abs($increment) / 3) * 3) % 3;

The ceil(abs($increment) / 3) * 3 bit just makes sure whatever is in the brackets is positive, regardless of what $increment is, so that you can add or subtract and it'll still work.
 
Last edited:
Back
Top Bottom