A number is called even if the number is divisible by 2 and is called odd if it is not divisible by 2. Given a number, we need to check whether it is odd or even in PHP.
Examples :
Input : 42 Output : Even Explanation: The number 42 is divisible by 2 Input : 39 Output : Odd Explanation: The number 39 is not divisible by 2
We can solve this problem in two different ways as described below:
-
Using modulo (%) operator: This is the simplest method of checking for even and odd and in this method, we simply check whether the number is divisible by 2 or not using the modulo ‘%’ operator.
Below program explains the above approach:
PHP
<?php
// PHP code to check whether the numberÂ
// is Even or Odd in Normal way
function
check(
$number
){
   Â
if
(
$number
% 2 == 0){
       Â
echo
"Even"
;Â
   Â
}
   Â
else
{
       Â
echo
"Odd"
;
   Â
}
}
Â
Â// Driver Code
$number
= 39;
check(
$number
)
?>
Output :
Odd
Time Complexity: O(1)
-
Recursive method: In the recursive approach, we reduce the number by 2 in each recursive call. If the final number is 0 then its even or else it is 1, the result will be odd.
Below is the implementation of above approach:PHP
<?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);Â Â Â Â Â Â Â Â
}
Â
Â// Driver Code
$number
= 39;
if
(check(
$number
))
   Â
echo
"Even"
;
else
   Â
echo
"Odd"
;
?>
Output :
Odd
Time Complexity: O(n)
-
Using Bit Manipulation:
In this method we will find bit-wise AND of the number with 1. If the bit-wise AND is 1, then the number is odd, else even.Below is the implementation of above idea.
PHP
<?php
// PHP code to check whether the numberÂ
// is Even or Odd using Bitwise Operator
function
check(
$number
)
{
    Â
ÂÂ Â Â Â
// One
   Â
$one
= 1;
    Â
ÂÂ Â Â Â
// Bitwise AND
   Â
$bitwiseAnd
=
$number
&
$one
;
    Â
ÂÂ Â Â Â
if
(
$bitwiseAnd
== 1)
   Â
{
       Â
echo
"Odd"
;Â
   Â
}
   Â
else
{
       Â
echo
"Even"
;
   Â
}
}
Â
Â// Driver Code
$number
= 39;
check(
$number
)
?>
Output :
Odd
Time Complexity: O(1)
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.