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

8 Answers

``````n & 1
``````

``````if ( \$num & 1 ) {
//odd
} else {
//even
}
``````
php variables numbers

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

``````\$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
}
``````

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

``````\$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>";
``````

``````0.041879177093506 seconds mod
0.15969395637512 seconds is_int
0.044223070144653 seconds & operator
``````

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

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

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

``````\$a=2;
if(\$a %2 == 0){
echo "<h3>This Number is <b>\$a</b> Even</h3>";
}else{
echo "<h3>This Number is <b>\$a</b> Odd</h3>";
}
``````

``````\$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';
``````

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

### Tags

php   variables   numbers