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.
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
=
for fractional speed improvement: $number % 2 === 0
Another option is a simple bit checking.
n & 1
for example:
if ( $num & 1 ) {
//odd
} else {
//even
}
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.
(bool)($number & 1)
or
(bool)(~ $number & 1)
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.
Jan 27, 2019 at 14:22
!== -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.
Jul 27, 2020 at 22:42
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
is_int
approach "smells" to me. It relies on the exact implementation details of integer division. I would avoid it, regardless of performance.
Jul 27, 2020 at 22:18
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.
in_array
which beats mod operator sometimes.
$num & 1
:). You could also do it hexadecimal: array(0, 2, 4, 6, 8, A, C, E, F) :D.
Feb 1, 2017 at 14:30
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.
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.
Jul 27, 2020 at 22:22
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.
Aug 29, 2020 at 20:23
All even numbers divided by 2 will result in an integer
$number = 4;
if(is_int($number/2))
{
echo("Integer");
}
else
{
echo("Not Integer");
}
is_int
approach "smells" to me. It relies on the exact implementation details of integer division. I would avoid it, regardless of performance.
Jul 27, 2020 at 22:18
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.
Try this,
$number = 10;
switch ($number%2)
{
case 0:
echo "It's even";
break;
default:
echo "It's odd";
}
case
statement with the mod test.
Jul 27, 2020 at 22:33
$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';
$number %2 = 1 if odd... so don't have to use not even...
$number = 27;
if ($number % 2 == 1) {
print "It's odd";
}
<?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
//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.";
}
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.";
}
}
?>
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
&
operator:$a=3; if($a&1){echo 'odd';}else{echo 'even';} //returns 'odd'