3

I'm not sure of the mathematical term for what I'm after, but I'm looking for a way in PHP to assign a variable to an integer which is a multiple of three. The multiple will start from numbers 1, 2 and 3. All integers will fall under one of three variables $varA, $varB and $varC. I think the modulus operator should be used, but I'm not sure how.

$varA could include numbers 1, 4, 7, 10, 13, 16, 19 etc.
$varB could include numbers 2, 5, 8, 11, 14, 17, 20 etc.
$varC could include numbers 3, 6, 9, 12, 15, 18, 21 etc.

I want to assign the number from an if statement, such as:

if( $number == (test for $varA) ) {
    $number = $varA
} else if( $number == (test for $varB) ) {
    $number = $varB
} else {
    $number = $varC
}
4

1 回答 1

18

是的,您需要模(不是模)运算符。这给出了除以三时的余数 - 0、1 或 2。

第一个测试是:

if ($number % 3 == 1)

您可能希望只评估一次并在 switch 语句中使用 - 正如下面其他 David 评论的那样,这稍微更有效:

switch ($number % 3) {
    case 1:
        $number = $varA;
        break;
    case 2:
        $number = $varB;
        break;
    case 0:
        $number = $varC;
        break;
}
于 2013-05-18T10:01:04.257 回答