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

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


当前回答

试试这个,

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

其他回答

你认为mod是个不错的开始,这是对的。下面是一个表达式,如果$number为偶数则返回true,如果为奇数则返回false:

$number % 2 == 0

适用于所有integerPHP值,参见算术操作符sphp。

例子:

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

输出:

它甚至

是的,使用mod

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

试试这个带有#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.";
    }
    }
?>

使用位操作: 在此方法中,您将找到带有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
)
<?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";
?>

因此,输出将是Odd