Simple function to see if a number is Even or Odd.

By | July 31, 2012

Sometimes you need to check if a number is even or odd. A simple way to do this is using the modulus operator (the %-sign). It will calculate and return the remainder when dividing a value with another value.

So how do you use that to find out if a number is even or odd?

 

As usual you need to understand the logic of the operation to be able to program a solution. In this case it’s really easy… The definition an even number is of course that it’s dividable by two (leaving no remainder). This is simple second grade school math.

So all we have to do is divide the number by 2 and check that the remainder is 0. Using the modulus operator this could look like this: 4 % 2 == 0. That operation will return TRUE, since dividing 4 by 2 will give the remainder of 0.

Sometimes you need to check a lot of numbers through out your application, and it might be convenient to have a function you can simply call whenever needed.
A very simple function, that takes one argument (number) could look like this:

function isEven($number)
{
	return ($number % 2 == 0);
}

You just call the function with the variable or number you need to check. Like this:

function isEven($number) { 	
	return ($number % 2 == 0); 
} 

$dude = 3;  
if (isEven($dude)) 	
	echo $dude." is an even number"; 
else 	
	echo $dude." is an odd number"; 

You could of course just use the modulus directly in your code, without a function since it holds very little code. But there might be other operations you want to do in there – like checking if the number is an integer and so on.

Also, putting often used code inside a good function with a self explanatory name – will increase the readability of your code.

Leave a Reply

Your email address will not be published. Required fields are marked *