Test if number is odd or even

PhpVariablesNumbers

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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 - Php

Another option is a simple bit checking.

n & 1

for example:

if ( $num & 1 ) {
  //odd
} else {
  //even
}

Solution 3 - Php

Yes using the mod

$even = ($num % 2 == 0);
$odd = ($num % 2 != 0);

Solution 4 - Php

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 - Php

(bool)($number & 1)

or

(bool)(~ $number & 1)

Solution 6 - Php

I did a bit of testing, and found that between mod, is_int and the &-operator, mod is the fastest, followed closely by the &-operator. is_int is nearly 4 times slower than mod.

I used the following code for testing purposes:

$number = 13;

$before = microtime(true);
for ($i=0; $i<100000; $i++) {
	$test = ($number%2?true:false);
}
$after = microtime(true);

echo $after-$before." seconds mod<br>";

$before = microtime(true);
for ($i=0; $i<100000; $i++) {
	$test = (!is_int($number/2)?true:false);
}
$after = microtime(true);

echo $after-$before." seconds is_int<br>";

$before = microtime(true);
for ($i=0; $i<100000; $i++) {
	$test = ($number&1?true:false);
}
$after = microtime(true);

echo $after-$before." seconds & operator<br>";

The results I got were pretty consistent. Here's a sample:

0.041879177093506 seconds mod
0.15969395637512 seconds is_int
0.044223070144653 seconds & operator

Solution 7 - Php

Another option is to check if the last digit is an even number :

$value = "1024";// A Number
$even = array(0, 2, 4, 6, 8);
if(in_array(substr($value, -1),$even)){
  // Even Number
}else{
  // Odd Number
}

Or to make it faster, use isset() instead of array_search :

$value = "1024";// A Number
$even = array(0 => 1, 2 => 1, 4 => 1, 6 => 1, 8 => 1);
if(isset($even[substr($value, -1)]){
  // Even Number
}else{
  // Odd Number
}

Or to make it more faster (beats mod operator at times) :

$even = array(0, 2, 4, 6, 8);
if(in_array(substr($number, -1),$even)){
  // Even Number
}else{
  // Odd Number
}

Here is the time test as a proof to my findings.

Solution 8 - Php

PHP is converting null and an empty string automatically to a zero. That happens with modulo as well. Therefor will the code

$number % 2 == 0 or !($number & 1)

with value $number = '' or $number = null result in true. I test it therefor somewhat more extended:

function testEven($pArg){
    if(is_int($pArg) === true){
	    $p = ($pArg % 2);
	    if($p === 0){
		    print "The input '".$pArg."' is even.<br>";
	    }else{
		    print "The input '".$pArg."' is odd.<br>";
	    }
    }else{
	    print "The input '".$pArg."' is not a number.<br>";
    }
}

The print is there for testing purposes, hence in practice it becomes:
function testEven($pArg){
    if(is_int($pArg)=== true){
        return $pArg%2;
    }
    return false;
}

This function returns 1 for any odd number, 0 for any even number and false when it is not a number. I always write === true or === false to let myself (and other programmers) know that the test is as intended.

Solution 9 - Php

All even numbers divided by 2 will result in an integer

$number = 4;
if(is_int($number/2))
{
   echo("Integer");
}
else
{
   echo("Not Integer");
}

Solution 10 - Php

This code checks if the number is odd or even in PHP. In the example $a is 2 and you get even number. If you need odd then change the $a value

$a=2;
if($a %2 == 0){
	echo "<h3>This Number is <b>$a</b> Even</h3>";
}else{
	echo "<h3>This Number is <b>$a</b> Odd</h3>";
}

Solution 11 - Php

> Check Even Or Odd Number Without Use Condition And Loop Statement.

This work for me..!

$(document).ready(function(){
    $("#btn_even_odd").click(function(){
        var arr = ['Even','Odd'];
        var num_even_odd = $("#num_even_odd").val();
        $("#ans_even_odd").html(arr[num_even_odd % 2]);
    });
});

<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <title>Check Even Or Odd Number Without Use Condition And Loop Statement.</title>
</head>
<body>
<h4>Check Even Or Odd Number Without Use Condition And Loop Statement.</h4>
<table>
    <tr>
        <th>Enter A Number :</th>
        <td><input type="text" name="num_even_odd" id="num_even_odd" placeholder="Enter Only Number"></td>
    </tr>
    <tr>
        <th>Your Answer Is :</th>
        <td id="ans_even_odd" style="font-size:15px;color:gray;font-weight:900;"></td>
    </tr>
    <tr>
        <td><input type="button" name="btn_even_odd" id="btn_even_odd" value="submit"></td>
    </tr>
</table>
</body>
</html>

Solution 12 - Php

I am making an assumption that there is a counter already in place. in $i which is incremented at the end of a loop, This works for me using a shorthand query.

$row_pos = ($i & 1) ? 'odd' : 'even';

So what does this do, well it queries the statement we are making in essence $i is odd, depending whether its true or false will decide what gets returned. The returned value populates our variable $row_pos

My use of this is to place it inside the foreach loop, right before i need it, This makes it a very efficient one liner to give me the appropriate class names, this is because i already have a counter for the id's to make use of later in the program. This is a brief example of how i will use this part.

<div class='row-{$row_pos}'> random data <div>

This gives me odd and even classes on each row so i can use the correct class and stripe my printed results down the page.

The full example of what i use note the id has the counter applied to it and the class has my odd/even result applied to it.:

$i=0;
foreach ($a as $k => $v) {
    
    $row_pos = ($i & 1) ? 'odd' : 'even';
    echo "<div id='A{$i}' class='row-{$row_pos}'>{$v['f_name']} {$v['l_name']} - {$v['amount']} - {$v['date']}</div>\n";

$i++;
}

in summary, this gives me a very simple way to create a pretty table.

Solution 13 - Php

Try this,

$number = 10;
 switch ($number%2)
 {
 case 0:
 echo "It's even";
 break;
 default:
 echo "It's odd";
 }

Solution 14 - Php

$number %2 = 1 if odd... so don't have to use not even...

$number = 27;

if ($number % 2 == 1) {
  print "It's odd";
}

Solution 15 - Php

Two simple bitwise functions, returning a 0 for False and 1 for True.

# is_odd: 1 for odd , 0 for even
odd = number & 1

# is_even: 1 for even , 0 for odd
even = number & 1 ^ 1

Solution 16 - Php

$before = microtime(true);

$n = 1000;	
$numbers = range(1,$n);

$cube_numbers = array_map('cube',$numbers);

function cube($n){		
	$msg ='even';		
	if($n%2 !=0){
		$msg = 'odd';
	}				
	return "The Number is $n is ".$msg;
}

foreach($cube_numbers as $cube){
	echo $cube . "<br/>";
}

$after = microtime(true);

echo $after-$before. 'seconds';

Solution 17 - Php

<?php
// Recursive function to check whether
// the number is Even or Odd 
function check($number){
    if($number == 0)
        return 1;
    else if($number == 1)
        return 0;
    else if($number<0)
        return check(-$number);
    else
        return check($number-2);        
}
  
// Check the number odd or even
$number = 35;
if(check($number))
    echo "Even";
else
    echo "Odd";
?>

So, the output will be Odd

Solution 18 - Php

//checking even and odd
$num =14;

$even = ($num % 2 == 0);
$odd = ($num % 2 != 0);

if($even){
    echo "Number is even.";
} else {
    echo "Number is odd.";
}

Solution 19 - Php

Try this one with #Input field

<?php
    //checking even and odd
    echo '<form action="" method="post">';
    echo "<input type='text' name='num'>\n";
    echo "<button type='submit' name='submit'>Check</button>\n";
    echo "</form>";
    
    $num = 0;
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["num"])) {
        $numErr = "<span style ='color: red;'>Number is required.</span>";
        echo $numErr;
        die();
      } else {
          $num = $_POST["num"];
      }
    
    
    $even = ($num % 2 == 0);
    $odd = ($num % 2 != 0);
    if ($num > 0){
        if($even){
            echo "Number is even.";
        } else {
            echo "Number is odd.";
        }
    } else {
        echo "Not a number.";
    }
    }
?>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1022585View Question on Stackoverflow
Solution 1 - PhpTim CooperView Answer on Stackoverflow
Solution 2 - PhpPawel DubielView Answer on Stackoverflow
Solution 3 - PhpAaron W.View Answer on Stackoverflow
Solution 4 - PhpTarikView Answer on Stackoverflow
Solution 5 - PhpOlegsView Answer on Stackoverflow
Solution 6 - PhpRuben CoolenView Answer on Stackoverflow
Solution 7 - PhpSubinView Answer on Stackoverflow
Solution 8 - PhpLoek BergmanView Answer on Stackoverflow
Solution 9 - PhpDavid S.View Answer on Stackoverflow
Solution 10 - PhpNarendra ChauhanView Answer on Stackoverflow
Solution 11 - PhpJD SavajView Answer on Stackoverflow
Solution 12 - PhpCodingInTheUKView Answer on Stackoverflow
Solution 13 - PhpSajjad HossainView Answer on Stackoverflow
Solution 14 - PhpjxwdView Answer on Stackoverflow
Solution 15 - PhpcinsightView Answer on Stackoverflow
Solution 16 - Phpuser2610558View Answer on Stackoverflow
Solution 17 - PhpBalajiView Answer on Stackoverflow
Solution 18 - PhpImran AzimView Answer on Stackoverflow
Solution 19 - PhpImran AzimView Answer on Stackoverflow