Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
捕捉PHP中高于或低于整数值的值_Php - Fatal编程技术网

捕捉PHP中高于或低于整数值的值

捕捉PHP中高于或低于整数值的值,php,Php,我需要有一个变量总是改变为在一定范围内(0-5),工作轮。例如,如果变量达到6,则应将其更改为0;如果它达到-1,则应更改为5。这是我的假象,有什么想法吗 function get_further_letter($index = 5, $number = 3, $direction = "encode") { $count = 5; switch ($direction) { case "encode": $index = $index + $n

我需要有一个变量总是改变为在一定范围内(0-5),工作轮。例如,如果变量达到6,则应将其更改为0;如果它达到-1,则应更改为5。这是我的假象,有什么想法吗

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
很抱歉说得含糊不清,我对如何实现这一点感到非常困惑,所以很难清楚地表达我的需求


在最后一个例子中,我得到了-2,特别是在我的例子中,该值将是一个数组索引。我不确定这是否真的会发生。

将值保持在
[0..n)
范围内的通用函数是:

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

双模运算是用来处理负数的。

不清楚你想做什么如果数字不在范围内,你想做什么?你到底想得到什么结果?它似乎起作用。你面临的问题是什么对不起,伙计们,我已经提供了更多的澄清-希望现在更清楚一点:哇,这样的answer、 非常成功。这段代码运行得非常好。@PeeHaa,我尝试了你的解决方案,但我找到了一个计算结果与预期不同的变量。但是Jack的解决方案是一个可靠的一行。非常感谢所有帮助过我的人!:)是的@Jamus已经指出我是个白痴谢谢:-)Nonono,你太棒了!我在尝试使用它时发现了一个问题。T谢谢你的帮助!非常感谢。