If a number is multiple of 3 starting at different numbers

27,211

Yes, you need the modulo (not modulus) operator. This gives the remainder when divided by three - either 0, 1 or 2.

The first test would be:

if ($number % 3 == 1)

You may wish to evaluate only once and use in a switch statement - as the other David comments below, this is marginally more efficient:

switch ($number % 3) {
    case 1:
        $number = $varA;
        break;
    case 2:
        $number = $varB;
        break;
    case 0:
        $number = $varC;
        break;
}
Share:
27,211
Fisu
Author by

Fisu

Updated on May 19, 2020

Comments

  • Fisu
    Fisu about 4 years

    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
    }