Best way to check for positive integer (PHP)?

前端 未结 20 2247
心在旅途
心在旅途 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;
    }
    

提交回复
热议问题