转换大于5的数字

时间:2011-10-07 03:56:10

标签: php numbers

我希望大于5的转换号码再次变为1-5,例如:

6 become 1
7 become 2
8 become 3
9 become 4

所以,如果我输入数字6-9到我的函数,它将转换为上面的解释。

my_function(6); //will become 1
my_function(7); //will become 2 and so on...

3 个答案:

答案 0 :(得分:6)

function my_function( $num ) {
    if ( $num % 5 === 0 ) {
         return 5;
    }
    return $num % 5;
}

当一个数字除以另一个数字时,模数运算符%返回余数。

答案 1 :(得分:6)

使用Modulus operator, %,它会给出除法的余数。

function RangeOneToFive($num)
{
   // Without the subtract and add this would range 0 to 4.
   return (($num - 1) % 5) + 1;
}

答案 2 :(得分:0)

function my_function( $num ) {
    ( $num % 5 === 0 ) ? $num = 5 : $num = $num % 5;
    return $num;
}