[PHP] [TUT] Check if a number is even

Status
Not open for further replies.

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,637
2,389
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.

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

Usage:
PHP:
<?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.

As I always say, I'm not the best at explaining things but I hope this was easy to understand.

- Mark
 
Status
Not open for further replies.

Users who are viewing this thread

Top