Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!
Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.
Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!
[Solved] PHP - Determine if a number is even or odd with modulus
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter
August 19, 2013 8:17 AM
It's the little tricks that make life easier - if you remember them
Here a trick to determine if a number is even or odd by determining what the modulus (left over after division) when we divide a number by 2 - Even numbers can be dividied by 2 and will result in a modulus (left over) of zero, odd numbers however will result in a modulus of 1:
<!--?php
<?php
// example nummer
$number = 25;
// with modulus (%) we determine if a number is odd or even
if( $odd = $number%2 )
{
// $odd == 1; left over or modulus of 1 indicates an ODD number
echo 'Odd number!';
}
else
{
// $odd == 0; left over or modulus of zero indicate an EVEN number
echo 'Even number!';
}
?>