PHP - Check if a number is Even, Odd or multiple of another

There are times when we need to check if a number is even, odd or multiple of another. Here are few methods to do the same.
May 12, 2013 PHP, code, php, snippets

While coding PHP applications, there are times when we need to check if a number is even, odd or multiple of another.

Here are few methods to do the same.

Method 1:

$number = 3;
if($number & 1){
    echo 'Odd number!';
}else{
    echo 'Even number!';
}

Method 2:

$number = 3;
if($number % 2){
    echo 'Odd number!';
}else{
    echo 'Even number!';
}

Method 3:

$number = 3;
echo ($number % 2 ? 'Even' : 'Odd');

Method 4:

Check if number is multiple of another. This can be used to float DIV elements and remove margin from the last ones.

for ($i=1; $i <= 10; $i++) {
	if($i % 2){
		echo $i.' is not multiple of 2';
	}else{
		echo $i.' is multiple of 2';
	}
	echo '<br />'; // Adds a line break.
}

If you know of another methods, do share these in comments.

  • Sajeǝd Hussain

    Thanks for the article..
    has been a great help.!