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.
Link to comment
Share on other sites

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.
Link to comment
Share on other sites

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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.