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 ?
Why don't you use the Modulus Operator?
Try this:
while ($s % 6 != 0) $s++;
Or is this what you meant?
<?
$s= <some_number>;
$k= $s % 6;
if($k !=0) $s=$s+6-$k;
?>
So you want the next multiple of 6, is that it?
You can divide your number by 6, then ceil it, and multiply it again:
$answer = ceil($foo / 6) * 6;
Simply run a while loop that will continue to loop (and increase the number) until the number is divisible by 6.
while ($number % 6 != 0) {
$number++;
}
For micro-optimisation freaks:
if ($num % 6 != 0)
$num += 6 - $num % 6;
More evaluations of %
, but less branching/looping. :-P
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;
$num += (6-$num%6)%6;
no need for a while loop! Modulo (%) returns the remainder of a division. IE 20%6 = 2. 6-2 = 4. 20+4 = 24. 24 is divisible by 6.