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

我试过一些剧本,但是…谷歌目前没有发送。


当前回答

使用位操作: 在此方法中,您将找到带有1的数字的逐位与。如果位与为1,则该数字为奇数,否则为偶数。

function odd($var){
    return $var & 1;
}
function even($var){
    return !($var&1);
}
$arr = range(1,10);

echo "Odd Numbers: ";
echo "<pre>";
    print_r(array_filter($arr2, 'odd'));
echo "<pre>";

echo "<br>Even Numbers: ";
echo "<pre>";
    print_r(array_filter($arr2, 'even'));
echo "</pre>";

输出将是:

Odd Numbers:
Array
(
    [0] => 1
    [2] => 3
    [4] => 5
    [6] => 7
    [8] => 9
)

Even Numbers: 
Array
(
    [1] => 2
    [3] => 4
    [5] => 6
    [7] => 8
    [9] => 10
)

其他回答

另一种方法是检查最后一位是否为偶数:

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

或者为了更快,使用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
}

或者让它更快(有时胜过mod操作符):

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

这是一个时间测试来证明我的发现。

我做了一些测试,发现在mod, is_int和&-操作符之间,mod是最快的,紧随其后的是&-操作符。 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

$number %2 = 1如果是奇数…所以不用用not even…

$number = 27;

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

试试这个,

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

试试这个带有#Input字段的

<?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.";
    }
    }
?>