View Full Version : php integer
Revan
09-07-2004, 05:13 AM
How can I check if an integer is an even number?
I want to have a submit button and for each of the users that clicks it, it adds their usernames to a field in a table.
However, I cannot have the # of users to be an uneven number (IE 1, 3, 5, 7 etc).
So there is my problem.
Anyone?
Tekton
09-07-2004, 07:08 AM
I'm sure there are prolly cleaner ways to write this, but....
if($value % 2 == 0)
{
// it's even
}else{
$value += 1; // or whatever
}
Colin F
09-07-2004, 07:40 AM
you could do something like this... if you don't find a better way :)
if (($number/2) == (intval(($number+1)/2))
{
//is even number
}
else
{
//is uneven number
}
Revan
09-07-2004, 02:33 PM
Cheers people :)
I tried both of them first with a single figured number, and they both worked fine.
I then tried with 20000000000000000000 just for the hell of it. Colins code said this was uneven, while Tektons said even.
Then I tried with 20000000000000000001 which reversedly Colins code called uneven, while Tektons called it even.
:p
Now I dont need such a high number, just 100 or so. And they both say thats even XD
Thanks again guys :)
filburt1
09-07-2004, 02:55 PM
Cheers people :)
I tried both of them first with a single figured number, and they both worked fine.
I then tried with 20000000000000000000 just for the hell of it. Colins code said this was uneven, while Tektons said even.
Then I tried with 20000000000000000001 which reversedly Colins code called uneven, while Tektons called it even.
:p
Now I dont need such a high number, just 100 or so. And they both say thats even XD
Thanks again guys :)
Tekton's method is by far more preferable (modulus division).
if ($number % 2 == 0)
...evaulates to true if the number is evenly divisible by 2 (i.e., even).
Dean C
09-07-2004, 03:37 PM
Also it's always nice to write a function for these things :)
function is_even($num)
{
if($number % 2 == 0)
{
return true;
}
else
{
return false;
}
}
Then to check if it's even use this:
$number = 2;
if(is_even($number))
{
echo 'it\'s even!';
}
else
{
echo 'it\'s not even!';
}
Revan
09-07-2004, 05:35 PM
Added the fucntion for future usage :)
But I feel pretty sure that the arguement in the function ($num in above) and the function coding ($number in above) should be equal ;) hehe
Dean C
09-07-2004, 05:45 PM
Yep you're write, I've been programming all day so that's my excuse ;)
vBulletin® v3.8.12 by vBS, Copyright ©2000-2025, vBulletin Solutions Inc.