I’m hoping someone could give me some input on how to improve this function. Its purpose is to evaluate whether a form input is a valid integer, and if not, either return a zero by default, or -1 if the second argument = true.
EDIT: Here is an updated version of the function I’m using. It seems the two most challenging parts are to ensure that an empty string doesn’t evaluate as 0 when expecting -1 for empty strings ($neg=true), and evaluating inputs with left padded zeros as integers and not octals.
function clean_integer($value, $neg=false)
{
if (!is_numeric($value)) {
if (!$neg) {
return 0;
else {
return -1;
}
}
$value = ltrim(trim($value), '0');
if (!$neg)
{
if ($value !== true && ((string)(int) $value) === ((string) $value)) {
return (int) $value;
}
else {
return 0;
}
}
else
{
if (!is_numeric($value)) {
return 0;
}
if ($value !== true && ((string)(int) $value) === ((string) $value)) {
return (int) $value;
}
else {
return -1;
}
}
}
I’ve been staring at this for too long and am convinced I’m making it terribly overcomplicated.
Why not cast it and use the is_int() method? – http://php.net/manual/en/function.is-int.php
To adapt it to your function