PHP check if variable is a whole number

后端 未结 20 972
感动是毒
感动是毒 2020-12-29 20:05

I have this PHP code:

$entityElementCount = (-($highScore-$totalKeywordCount))/0.29;

What i want to know is, how to check whether $

20条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 20:41

    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)"
    

提交回复
热议问题