Test if number is odd or even
472,247
Solution 1
You were right in thinking mod was a good place to start. Here is an expression which will return true if $number
is even, false if odd:
$number % 2 == 0
Works for every integerPHP value, see as well Arithmetic OperatorsPHP.
Example:
$number = 20;
if ($number % 2 == 0) {
print "It's even";
}
Output:
It's even
Solution 2
Another option is a simple bit checking.
n & 1
for example:
if ( $num & 1 ) {
//odd
} else {
//even
}
Solution 3
Yes using the mod
$even = ($num % 2 == 0);
$odd = ($num % 2 != 0);
Solution 4
While all of the answers are good and correct, simple solution in one line is:
$check = 9;
either:
echo ($check & 1 ? 'Odd' : 'Even');
or:
echo ($check % 2 ? 'Odd' : 'Even');
works very well.
Solution 5
(bool)($number & 1)
or
(bool)(~ $number & 1)
Related videos on Youtube
Author by
user1022585
Updated on February 16, 2022Comments
-
user1022585 about 2 years
What is the simplest most basic way to find out if a number/variable is odd or even in PHP? Is it something to do with mod?
I've tried a few scripts but.. google isn't delivering at the moment.
-
Marc B over 12 yearsmod is the generic shorthand term for 'modulo', aka modular arithmetic
-
ashleedawg almost 5 yearsMore info here including: To determine odd or even it's faster and more efficient to use the bitwise
&
operator:$a=3; if($a&1){echo 'odd';}else{echo 'even';} //returns 'odd'
-
-
Martijn almost 11 yearsIf you use this in loops or large quantities, you might want to consider the bitcheck suggested by Arius2038, which is very fast. The bitcheck is my prefered method for odd/even checks.
-
thomasrutter over 10 yearsThis would definitely be the fastest way when using integers in a language like C, by a large margin. Has anyone done benchmarks to determine if this is true also for PHP?
-
Pawel Dubiel over 10 yearson my server ( 5.4.4 / cli / no opcache / i7 ) the "&" is about 10% faster then mod ( tested on array with random integer values )
-
danhere over 10 yearsThis is a bitwise operator I believe so unless you know what you're doing with that fancyness, I would avoid this syntax.
-
Rolf over 10 yearsIt's probably the fastest way, if the PHP engine was well coded.
-
Subin about 10 yearsTo Downvoter : May I please know why you downvoted ?
-
Robbiegod about 10 yearsI'd say this is the fastest and most straight forward way. Perfect.
-
snlan over 9 yearsWorks fine but I'm just wondering whats the logic behind this? Why is it that a value of true is given if "10 == 0" ?
-
crdunst over 9 yearsThe logic is that any even number is divisible by 2 with no remainder. If you used $number % 10, and your $number was 20, it would return true, but not if your $number was 22. You could use $number % 10 if you were trying to find every 10th item in a loop for example.
-
Hendry Tanaka over 9 years@Tim, if 5%2=1. The logica is 2*2+1=5.How to get the 2 in php?
-
Joey Sabey about 9 years@Hendry - what are you asking exactly? How to get the quotient for a division as a whole number, or...? If that is what you mean, you just need to floor() the result; floor(5/2)=2
-
grantwparks about 9 yearsIt's very expensive, compared to other methods.
-
Subin about 9 years@grantwparks Well, the difference between using isset & mod is only 0.5007 seconds. But, array_search is very expensive.
-
grantwparks about 9 yearsThose aren't seconds in the test, they're actually much less. So on the surface, it sounds reasonable. But think of this: in the results, mod came out at 2.0xxxx units of time. While isset came out at 2.5xxxx units of time. That's a 25% increase in execution time. How reasonable does it sound now ;)
-
Subin almost 9 years@grantwparks Well, you're right. This answer is only for information and I suggest using mod.
-
kasimir almost 9 yearsMight I suggest a triple
=
for fractional speed improvement:$number % 2 === 0
-
kasimir almost 9 yearsAbove link is dead. Here's another good explanation: catonmat.net/blog/low-level-bit-hacks-you-absolutely-must-know
-
Subin about 8 years@grantwparks I have update the code to include
in_array
which beats mod operator sometimes. -
Matthijs Wessels about 7 yearsInteresting way of thinking though. It's basically the decimal version of
$num & 1
:). You could also do it hexadecimal: array(0, 2, 4, 6, 8, A, C, E, F) :D. -
Jonas Lundman over 6 yearsI have to admire the syntax, things that works without knowing why, gives you a reminder of how small we are in the world of fysics, math and, well, just add a row on number 1, not 2...
-
GordonM about 6 yearsWhat does this answer add that the originally accepted answer doesn't?
-
GordonM about 6 yearsWhat does this answer add that the originally accepted answer doesn't?
-
Imran Azim about 6 yearsit takes input from the user and take decision on that input.
-
GordonM about 6 yearsSo nothing really.
-
Martin James over 5 yearsI use bitwise operators in JS quite a bit. For example
if (~string.indexOf("@")) {}
instead ofif (string.indexOf("@") !== -1) {}
. I prefer to see conditions result in a simple true or false. But yes, it can be a little confusing to people that aren't familiar with this syntax. -
ToolmakerSteve almost 4 yearsNOTE: to also handle float values, testing nearest integer, do
if ((int)round($number) % 2 === 0)
. If omit "round", this is truncation, which I don't recommend: a floating point number could display as if it were a whole value (e.g.1.0
), yet be a hair below that whole value. If really need truncation, then add a small offset:if ((int)($number + 0.00001) % 2 === 0)
. The amount of offset to add depends on your circumstances. -
ToolmakerSteve almost 4 yearsPlease don't do this, IMHO. Relying on the decimal string representation of an integer is not a good way to think about numeric operations. If anyone on my team used this technique, I would be quite concerned about their grasp of mathematics; suggest they speak with another programmer next time they encountered a math problem. If you want a more specific complaint, this technique doesn't generalize to other divisors: Suppose we next need to know whether a value is divisible by 3. You've gone down a dead-end road.
-
ToolmakerSteve almost 4 yearsThe
is_int
approach "smells" to me. It relies on the exact implementation details of integer division. I would avoid it, regardless of performance. -
ToolmakerSteve almost 4 yearsThe
is_int
approach "smells" to me. It relies on the exact implementation details of integer division. I would avoid it, regardless of performance. -
ToolmakerSteve almost 4 yearsCAUTION: In php, the "looseness" of the language means one often encounters an integer represented as a string (which of course fails
is_int
test). For example, when interacting with SQL on a website. I would instead useis_numeric
, which will reject null and empty string. However, that will allow floats and float-representation-strings, so may need additional tests to be thorough. -
ToolmakerSteve almost 4 yearsThis is a nice demonstration of using
case
statement with the mod test. -
ToolmakerSteve almost 4 years@MartinJames: re "I prefer to see conditions result in a simple true or false." which is exactly what techniques such as
!== -1
or=== 0
do. Here's the problem with using bitwise operators to do anything other than a bitwise operation: you are placing a burden on the reader, to understand your intent. At minimum, you should add a comment anywhere you use that technique. Or write a well-named function and call it. Smells like an unnecessary micro-optimization to me. Seriously, if I was working with you, I would ask you to change to standard usage of obvious operators and expressions. -
Loek Bergman almost 4 yearsThis answer is returned with the question for a basic answer in mind. You are absolutely right that in a normal application extra code is required, but that is out of scope of the question. My main point in this answer is that the operator === should be used instead of the operator ==. The last operator will return 'even' when the input is 0, "", null or false.
-
ToolmakerSteve over 3 yearsOK. Suggesting
is_int
is good. In production code I might expand this toif (!is_numeric($pArg)) ..throw-some-exception..; $p = (int)$pArg; return ($p % 2) == 0;
Bug: you omitted== 0
from last snippet:return $pArg%2;
returns0
(so "false") for even numbers. Minor nit: You use===
in a place where it is not at all needed.is_int
can only returntrue
orfalse
, so=== true
can be safely omitted there. -
Loek Bergman over 3 yearsSuggestion: Exception throwing is very important in constructing robust code, I agree. Yet in some functions I wonder if it is wise to throw an exception and return a false instead. Throwing an exception implies that the process ends. Are mistakes in all functions really that important? Bug: Could be a bug if I test with ==, yet I always test with ===. Then is 0 different from false. Minor nit: Correct that it can be omitted. I write it in PHP though, to show the other programmers that this is the check to be executed. It is for maintenance purposes only.
-
Loek Bergman over 3 yearsThe code returns a value. In this case 0, 1 or false. The caller of this function has to test using the === in order to make this distinction. It would be more robust code indeed when the function returns 2,3 or false like this 'return ($pArg % 2) === 0 ? 2 : 3;'. Even if the caller uses == then will these values never create any confusion.
-
Loek Bergman over 3 yearsThe function answers two questions: is it an int? If so, is it odd or even? Hence is a tri-state value required. With your expert knowledge you should have known. I programmed in Java and had to get used to the fact that 0 is not automatically different from false. I use true/false for primitive values and null for scalar ones. And always the === - operator. In Java null is an object, so I don't use it when testing primitive values.
-
ToolmakerSteve over 3 yearsThank you for editing the answer to clarify the values returned by your function.
-
Quentin over 2 yearsThat's a ludicrously inefficient approach to solving the problem, so much so that it will fall over on large numbers as it will run out of memory.