Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PHP] Check if a number is even [TUT]
#1
In this tutorial I am going to show you how to check if a number is even or not, it's nothing special but it can come in handy at some point, for example - when you are doing alternate table rows.

Code:
<?php
function iseven( $num )
{
    return ( $num % 2 == 0 ) ? true : false;
}
?>

Usage:
Code:
<?php
$numbers = array( 1, 3, 8, 5, 64, 73 );
foreach ( $numbers as $number )
{
    echo '<strong>' . $number . '</strong> is ' . ( iseven( $number ) ? 'even' : 'not even' ) . '<br />';
}
?>

How it works:
The function contains an operator called a modulus which divides a number by another number and returns another number. In this case, I have made the modulus divide '$num' (the number we want to check is even or not) by 2, if the result of that sum is 0 then the number is even, if it is not equal to 0 then the number is not even. So because an odd number can not be divided by 2 without returning another odd number, the function returns 'false' meaning that the number is odd.

Thanks,
Derpec
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)