I’m not going to bother you with mathematics. I’m just going to present two functions that can be used within your PHP scripts to determine whether a number is odd or even. There are more reasons than one to know when a number is odd or even, and more than one way to determine it, but using functions makes it easier to do it when you’re traversing an array.
Arrays are numerically stored beginning with the number and key of 0, making the first element an even number, so I’ll start with the even number function. Since PHP is frequently updated with point versions, you never know when a particular function is going to become a part of the language, so it’s always best to check to see if the function doesn’t exist before using it, even if it’s an obscure function name (because what’s obscure to you may not be obscure to others).
The “is_even” function
if ( !function_exists( 'is_even' ) ) {
function is_even( $num ) {
if ( $num % 2 == 0 ) {
return true;
}
return false;
}
}
To use, simply call is_even( $num ), substituting $num with your variable.
The “is_odd” function
if ( !function_exists( 'is_odd' ) ) {
function is_odd( $num ) {
if ( $num % 2 ) {
return true;
}
return false;
}
}
To use, simply call is_odd( $num ), substituting $num with your variable.
Why Two Different Functions
I use two different functions because it’s easier for me to remember is_odd( $num ) or is_even( $num ) than remembering to use the NOT operator. It’s simpler to use !is_odd( $num ) to check for an even number, but not easier to remember.
By the way, both of these evaluate to true for an odd number:
$num % 2
$num & 1
Both of these evaluate to true for an even number:
$num % 2 == 0
!( $num & 1 )
I’m sure there are other ways to determine odd and even numbers, but I’m not interested in discovering them.