PHP check if variable is a whole number
$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;
if (ctype_digit($entityElementCount) ){
// (ctype_digit((string)$entityElementCount)) // as advised.
print "whole number\n";
}else{
print "not whole number\n";
}
I would use intval function like this:
if($number === intval($number)) {
}
Tests:
var_dump(10 === intval(10)); // prints "bool(true)"
var_dump("10" === intval("10")); // prints "bool(false)"
var_dump(10.5 === intval(10.5)); // prints "bool(false)"
var_dump("0x539" === intval("0x539")); // prints "bool(false)"
Other solutions
1)
if(floor($number) == $number) { // Currently most upvoted solution:
Tests:
$number = true;
var_dump(floor($number) == $number); // prints "bool(true)" which is incorrect.
2)
if (is_numeric($number) && floor($number) == $number) {
Corner case:
$number = "0x539";
var_dump(is_numeric($number) && floor($number) == $number); // prints "bool(true)" which depend on context may or may not be what you want
3)
if (ctype_digit($number)) {
Tests:
var_dump(ctype_digit("0x539")); // prints "bool(false)"
var_dump(ctype_digit(10)); // prints "bool(false)"
var_dump(ctype_digit(0x53)); // prints "bool(false)"
if (floor($number) == $number)
I know this is old, but I thought I'd share something I just found:
Use fmod and check for 0
$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;
if (fmod($entityElementCount,1) !== 0.0) {
echo 'Not a whole number!';
} else {
echo 'A whole number!';
}
fmod is different from % because if you have a fraction, % doesn't seem to work for me (it returns 0...for example, echo 9.4 % 1;
will output 0
). With fmod, you'll get the fraction portion. For example:
echo fmod(9.4, 1);
Will output 0.4