php doesn't have a built in "is_even()" function, but you can make your own:
PHP Code:
/**
* bool is_even ( integer )
*
* @param $int The integer value being evaluated
* @return Returns true if $int is even. Returns false if $int is odd
*
*/
function is_even($int) {
if ( !is_int($int) ) {
trigger_error('The is_even() function only accepts integers.', E_USER_WARNING);
return;
// Or get rid of trigger_error(xxx) and replace it with: return false;
// to accept any input. This will cause odd numbers and decimals
// to return false.
}
$result = $int % 2 == 0 ? true : false;
return $result;
}
I don't know how well you know php, but when I first started learning php I would see a function that someone wrote for me and not really understand it, so I'll explain mine.
is_even() as I wrote it, accepts an integer value only. The first part of the function checks to see if the input value is an integer, if not it will cause an error message to be displayed. If you want to change the type of error that is displayed, you can change E_USER_WARNING to one of the other E_USER constants http://www.php.net/manual/en/errorfunc.constants.php .
If the input is an integer, the next part of the function is executed. I used the ternary operator:
http://www.php.net/manual/en/languag...arison.ternary
The value assigned to $result will depend on whether or not $int % 2 == 0 evaluates to true or false. If true, the first value after the ? will be assigned to $result, if false, the second value will be assigned.
$int % 2 uses the modulus operator %. This means that the remainder of $int / 2 will be returned. When an even integer is divided by 2, there is never a remainder, so the result is 0. An odd integer divided by 2 has a remainder of 1. So if $int % 2 == 0, $int must be even, and this statement is true, so "$result = $int % 2 == 0 ? true : false" will assign true, the first value after the ?, to $result.
The function then returns $result as either true or false.
PHP Code:
$int = 23;
if ( is_even($int) ) {
echo "$int is an even number.";
} else {
echo "$int is an odd number.";
}
The above will output "23 is an odd number."
There are some decimal numbers that will divide by 2 without a remainder, so this function needs to only accept integer values. You could change the trigger_error() if you to accept decimals and return false. Just get rid of "trigger_error(XXXX);" and put "return false;"
Good luck,
Jason
Bookmarks