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

Spread the love

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

Here are a 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 the 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 method, do share these in the comments.

contact us

get information for your project.

Leave a Reply

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

 
Enquiry Now
iogoos-logo

Our consultants will respond back within 8 business hours or less.

X