03-04-2013, 03:30 AM

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.

Usage:

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

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