Rutger Claes wrote:
Paul E Collins wrote:
Given a string variable (form input), how can I determine whether it
represents a valid integer?
is_numeric is true for floats as well as integers, and is_int always
fails on a string.
intval( $string ) == $string
works for me...
Depends on how strict you need to be...
intval($n)==$n will return TRUE if you have a float like 5.0
However, if you use:
intval($n)===$n
Then the string '5' would fail...
If you need to reject floats, but need to use strings as well, you'll
really need to do something like this (pulled from something I did a
couple years ago):
/**
* input_intval
*
* Takes a variable and returns the integer value that corresponds
* to the value. If the value cannot be represented by an integer,
* FALSE is returned.
*
* @param $n [mixed] Value to check.
* @result Returns an integer value or FALSE. Check for FALSE using
* if(input_intval($n)===FALSE) in case of integer < 0 being
* returned.
**/
function input_intval($n){
if(is_numeric($n)){
if(is_int($n)){
return $n;
}else{
// this is a float...
if(intval($n)==$n){
return $n;
}else{
return FALSE;
}
}
}else{
return FALSE;
}
}
--
Justin Koivisto -
sp**@koivi.com http://www.koivi.com