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)
Share:
472,247

Related videos on Youtube

user1022585
Author by

user1022585

Updated on February 16, 2022

Comments

  • user1022585
    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
      Marc B over 12 years
      mod is the generic shorthand term for 'modulo', aka modular arithmetic
    • ashleedawg
      ashleedawg almost 5 years
      More 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
    Martijn almost 11 years
    If 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
    thomasrutter over 10 years
    This 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
    Pawel Dubiel over 10 years
    on my server ( 5.4.4 / cli / no opcache / i7 ) the "&" is about 10% faster then mod ( tested on array with random integer values )
  • danhere
    danhere over 10 years
    This is a bitwise operator I believe so unless you know what you're doing with that fancyness, I would avoid this syntax.
  • Rolf
    Rolf over 10 years
    It's probably the fastest way, if the PHP engine was well coded.
  • Subin
    Subin about 10 years
    To Downvoter : May I please know why you downvoted ?
  • Robbiegod
    Robbiegod about 10 years
    I'd say this is the fastest and most straight forward way. Perfect.
  • snlan
    snlan over 9 years
    Works 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
    crdunst over 9 years
    The 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
    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
    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
    grantwparks about 9 years
    It's very expensive, compared to other methods.
  • Subin
    Subin about 9 years
    @grantwparks Well, the difference between using isset & mod is only 0.5007 seconds. But, array_search is very expensive.
  • grantwparks
    grantwparks about 9 years
    Those 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
    Subin almost 9 years
    @grantwparks Well, you're right. This answer is only for information and I suggest using mod.
  • kasimir
    kasimir almost 9 years
    Might I suggest a triple = for fractional speed improvement: $number % 2 === 0
  • kasimir
    kasimir almost 9 years
    Above link is dead. Here's another good explanation: catonmat.net/blog/low-level-bit-hacks-you-absolutely-must-kn‌​ow
  • Subin
    Subin about 8 years
    @grantwparks I have update the code to include in_array which beats mod operator sometimes.
  • Matthijs Wessels
    Matthijs Wessels about 7 years
    Interesting 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
    Jonas Lundman over 6 years
    I 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
    GordonM about 6 years
    What does this answer add that the originally accepted answer doesn't?
  • GordonM
    GordonM about 6 years
    What does this answer add that the originally accepted answer doesn't?
  • Imran Azim
    Imran Azim about 6 years
    it takes input from the user and take decision on that input.
  • GordonM
    GordonM about 6 years
    So nothing really.
  • Martin James
    Martin James over 5 years
    I use bitwise operators in JS quite a bit. For example if (~string.indexOf("@")) {} instead of if (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
    ToolmakerSteve almost 4 years
    NOTE: 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
    ToolmakerSteve almost 4 years
    Please 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
    ToolmakerSteve almost 4 years
    The is_int approach "smells" to me. It relies on the exact implementation details of integer division. I would avoid it, regardless of performance.
  • ToolmakerSteve
    ToolmakerSteve almost 4 years
    The is_int approach "smells" to me. It relies on the exact implementation details of integer division. I would avoid it, regardless of performance.
  • ToolmakerSteve
    ToolmakerSteve almost 4 years
    CAUTION: 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 use is_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
    ToolmakerSteve almost 4 years
    This is a nice demonstration of using case statement with the mod test.
  • ToolmakerSteve
    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
    Loek Bergman almost 4 years
    This 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
    ToolmakerSteve over 3 years
    OK. Suggesting is_int is good. In production code I might expand this to if (!is_numeric($pArg)) ..throw-some-exception..; $p = (int)$pArg; return ($p % 2) == 0; Bug: you omitted == 0 from last snippet: return $pArg%2; returns 0 (so "false") for even numbers. Minor nit: You use === in a place where it is not at all needed. is_int can only return true or false, so === true can be safely omitted there.
  • Loek Bergman
    Loek Bergman over 3 years
    Suggestion: 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
    Loek Bergman over 3 years
    The 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
    Loek Bergman over 3 years
    The 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
    ToolmakerSteve over 3 years
    Thank you for editing the answer to clarify the values returned by your function.
  • Quentin
    Quentin over 2 years
    That'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.