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.
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.