None of the standard functions (is_numeric / is_float / ctype_digit) seem to give me the right results without allowing hex values while still allowing comma separators.1,234.56
I could have gone with regular expressions, but I was hoping I could achieve this task without going that way. It's also worth noting that I'm not interested if it is actually valid, just that it doesn't contain any other characters.
Code: Select all
<?php
$test = array("123", "123.45", "one.34", "123.45.67", "one", 12.52, "", "1,234.50", "1,234,567.89");
foreach ($test as $test_val) {
echo "Is $test_val an integer? ";
if(isNumber($test_val)) echo " Yes"; else echo "No";
echo "<br><br>";
}
function isNumber($value) {
@list($integer, $remainder) = explode(".", $value);
$int_segment = explode(",", $integer);
foreach($int_segment as $segment) if(!ctype_digit($segment)) return false;
if(!is_null($remainder) && !ctype_digit($remainder)) return false;
// echo "( evaluates as " . implode(",", $int_segment) . ".$remainder )";
return true;
}
?>Any thoughts on this? Potential issues or problems? Should I just use regular expressions?Is 123 an integer? ( evaluates as 123. ) Yes
Is 123.45 an integer? ( evaluates as 123.45 ) Yes
Is one.34 an integer? No
Is 123.45.67 an integer? ( evaluates as 123.45 ) Yes
Is one an integer? No
Is 12.52 an integer? ( evaluates as 12.52 ) Yes
Is an integer? No
Is 1,234.50 an integer? ( evaluates as 1,234.50 ) Yes
Is 1,234,567.89 an integer? ( evaluates as 1,234,567.89 ) Yes
Thanks for reading.