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

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


当前回答

是的,使用mod

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

其他回答

试试这个,

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

检查偶数或奇数不使用条件和循环语句。

这对我很有用!

$(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>

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

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

n & 1

例如:

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

or

(bool)(~ $number & 1)