checking if a number is divisible by 6 PHP


Question

I want to check if a number is divisible by 6 and if not I need to increase it until it becomes divisible.

how can I do that ?

1
49
1/29/2018 2:43:44 AM

Accepted Answer

if ($number % 6 != 0) {
  $number += 6 - ($number % 6);
}

The modulus operator gives the remainder of the division, so $number % 6 is the amount left over when dividing by 6. This will be faster than doing a loop and continually rechecking.

If decreasing is acceptable then this is even faster:

$number -= $number % 6;
118
5/9/2019 4:05:14 PM

if ($variable % 6 == 0) {
    echo 'This number is divisible by 6.';
}:

Make divisible by 6:

$variable += (6 - ($variable % 6)) % 6; // faster than while for large divisors

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon