Best way to check for positive integer (PHP)?

前端 未结 20 2266
心在旅途
心在旅途 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 18:52

    The best way for checking for positive integers when the variable can be INTEGER or STRING representing the integer:

     if ((is_int($value) || ctype_digit($value)) && (int)$value > 0 ) { // int }
    

    is_int() will return true if the value type is integer. ctype_digit() will return true if the type is string but the value of the string is an integer.

    The difference between this check and is_numeric() is that is_numeric() will return true even for the values that represent numbers that are not integers (e.g. "+0.123").

提交回复
热议问题