Best way to check for positive integer (PHP)?

前端 未结 20 2198
心在旅途
心在旅途 2020-12-02 18:34

I need to check for a form input value to be a positive integer (not just an integer), and I noticed another snippet using the code below:

$i = $user_input_v         


        
相关标签:
20条回答
  • 2020-12-02 19:08

    Rather than checking for int OR string with multiple conditions like:

    if ( ctype_digit($i) || ( is_int($i) && $i > 0 ) )
    {
        return TRUE;
    }
    

    you can simplify this by just casting the input to (string) so that the one ctype_digit call will check both string and int inputs:

    if( ctype_digit( (string)$i ) )
    {
        return TRUE;
    }
    
    0 讨论(0)
  • 2020-12-02 19:09

    All these answers overlook the fact that the requestor may checking form input.
    The is_int() will fail because the form input is a string.
    is_numeric() will be true also for float numbers.
    That is why the $i == round($i) comes in as it checks for the input being a whole number.

    0 讨论(0)
  • 2020-12-02 19:11

    In addition to all the other answers: You are probably looking for ctype_digit. It looks for a string containing only digits.

    0 讨论(0)
  • 2020-12-02 19:14

    The other best way to check a Integer number is using regular expression. You can use the following code to check Integer value. It will false for float values.

    if(preg_match('/^\d+$/',$i)) {
      // valid input.
    } else {
      // invalid input.
    }
    

    It's better if you can check whether $i > 0 too.

    0 讨论(0)
  • 2020-12-02 19:15

    the difference between your two code snippets is that is_numeric($i) also returns true if $i is a numeric string, but is_int($i) only returns true if $i is an integer and not if $i is an integer string. That is why you should use the first code snippet if you also want to return true if $i is an integer string (e.g. if $i == "19" and not $i == 19).

    See these references for more information:

    php is_numeric function

    php is_int function

    0 讨论(0)
  • 2020-12-02 19:15
        preg_match('{^[0-9]*$}',$string))
    

    and if you want to limit the length:

        preg_match('{^[0-9]{1,3}$}',$string)) //minimum of 1 max of 3
    

    So pisitive int with a max length of 6:

        if(preg_match('{^[0-9]{1,6}$}',$string)) && $string >= 0)
    
    0 讨论(0)
提交回复
热议问题