checking if a number is divisible by 6 PHP

Utku Dalmaz picture Utku Dalmaz · Jan 19, 2010 · Viewed 110k times · Source

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 ?

Answer

ZoFreX picture ZoFreX · Jan 19, 2010
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;