Jump to content

How to tell if a variable is a multiple of 2, 3, 4 etc


doni49

Recommended Posts

Recently, I needed to figure out if a number is a multiple of another number.

i.e. is $test a multiple of 5, is it a multiple of 7 etc.  I thought I'd share the results.

[code]
//if $test is a multiple of 7 then the following will return true.
is_int($test/7);
[/code]

The reason for this is that if you divide a number by another number and it returns an integer, then it was evenly divisible by that number.  If dividing doesn't result in an integer then it's a decimal value which means that it wasn't evenly divisible by that number.
Okay from what I can see $test % 7 would return TRUE if NOT a multiple of 7 and FALSE if it IS a multiple of 7.

Well there's two simple ways thanks.  I hunted and hunted then it dawned on me that i could just divide it and see if the result was an integer.
that's what modulus is. it's the remainder after division has been performed - so it actually returns a number, not true/false.

[code]
<?php
echo 15 % 7; // gives 1
echo 14 % 7; // gives 0
echo 8 % 7; // gives 1
?>
[/code]

so in your case, you're actually checking to see if the result is zero
cheers

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.