2

I need to have a variable always changed to be within a certain range (0-5), working on rounds. For instance, if the variable hits 6, it should be changed to 0; if it hits -1, it should be changed to 5. Here's my pseudo, any ideas?

function get_further_letter($index = 5, $number = 3, $direction = "encode") {
    $count = 5;
    switch ($direction) 
    {
    case "encode":
        $index = $index + $number; //pushes the value of index to 8
        break;
    }
    // Start my attempt
    while ($index > $count)
    {
        $index = $index - $count;
    }
    // End my attempt
    return $index;
}

>> get_further_letter(5, 3); // 5 + 3 = 8, 8 is 1r3, so keep r3 as 0, 1, 2
2
>> get_further_letter(5, 4); // 5 + 4 = 9, 9 is 1r4, so keep r4 as 0, 1, 2, 3
3
>> get_further_letter(5, -7); // 5 + -7 = -2, -2 is -1r-2, so keep r-2 as 0, 1, 2, 3
4

Sorry for being vague, I'm very confused about how to get this to work, so it's a little difficult to articulate my requirements.

I got -2 for the last example as in my case specifically the value will be an array index. I'm not sure if this is actually going to happen.

Jamus
  • 865
  • 4
  • 11
  • 28

1 Answers1

3

The generic function that will keep a value within the range of [0 .. n) is this:

function fn($x, $n)
{
    return ($x % $n + $n) % $n;
}

The double modulo is to deal with negative numbers.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 1
    Wow. Such answer. Great success. – PeeHaa Dec 19 '13 at 13:12
  • This code worked perfectly. @PeeHaa, I tried your solution, but I hit a variable it calculated differently than intended. But Jack's solution is a solid one-liner. Big thanks to everyone who helped! :) – Jamus Dec 19 '13 at 14:33
  • Yes @Jamus already pointed out I am an idiot thanks :-) – PeeHaa Dec 19 '13 at 14:38
  • 1
    Nononononono, you're amazing! I just found an issue when trying to use it. Thanks for your help all the same! Much appreciated. – Jamus Dec 19 '13 at 14:43