php 测试数字是奇数还是偶数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7959247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:41:42  来源:igfitidea点击:

Test if number is odd or even

phpvariablesnumbers

提问by user1022585

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?

在 PHP 中找出数字/变量是奇数还是偶数的最简单最基本的方法是什么?跟mod有关系吗?

I've tried a few scripts but.. google isn't delivering at the moment.

我已经尝试了一些脚本,但 .. 谷歌目前没有提供。

回答by Tim Cooper

You were right in thinking mod was a good place to start. Here is an expression which will return true if $numberis even, false if odd:

您认为 mod 是一个很好的起点,这是正确的。这是一个表达式,如果$number是偶数,则返回 true,如果是奇数,则返回false:

$number % 2 == 0

Works for every integerPHPvalue, see as well Arithmetic OperatorsPHP.

适用于每个整数PHP值,另请参阅算术运算符PHP

Example:

例子:

$number = 20;
if ($number % 2 == 0) {
  print "It's even";
}

Output:

输出:

It's even

它甚至

回答by Pawel Dubiel

Another option is a simple bit checking.

另一种选择是简单的位检查。

n & 1

for example:

例如:

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

回答by Aaron W.

Yes using the mod

是的,使用 mod

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

回答by Tarik

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.

效果很好。

回答by Olegs

(bool)($number & 1)

or

或者

(bool)(~ $number & 1)

回答by Subin

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:

或者为了让它更快,使用isset()而不是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 operatorat times) :

或者让它更快有时节拍mod operator):

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

Here is the time testas a proof to my findings.

这是时间测试,以证明我的发现。

回答by Ruben Coolen

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

我做了一些测试,发现在 modis_int&-operator 之间,mod 是最快的,其次是 &-operator。 is_int比mod慢近4倍。

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

回答by David S.

All even numbers divided by 2 will result in an integer

所有偶数除以 2 将得到一个整数

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

回答by sumit

//for numbers n [0,1,2,3,4....]

if((n+2)%2==1) {
   //odd
}else {
  //even
}

Zero is an even number. In other words, its parity—the quality of an integer being even or odd—is even. The simplest way to prove that zero is even is to check that it fits the definition of "even": it is an integer multiple of 2, specifically 0 × 2. As a result, zero shares all the properties that characterize even numbers: 0 is divisible by 2, 0 is surrounded on both sides by odd numbers, 0 is the sum of an integer (0) with itself, and a set of 0 objects can be split into two equal sets. from http://en.wikipedia.org/wiki/Parity_of_zero

零是偶数。换句话说,它的奇偶性——整数是偶数还是奇数——是偶数。证明零是偶数的最简单方法是检查它是否符合“偶数”的定义:它是 2 的整数倍,特别是 0 × 2。因此,零具有所有表征偶数的属性:0能被2整除,0两边被奇数包围,0是一个整数(0)与其自身的和,0个物体的集合可以分成两个相等的集合。来自http://en.wikipedia.org/wiki/Parity_of_zero

回答by jd savaj

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>