Best way to check for positive integer (PHP)?

前端 未结 20 2305
心在旅途
心在旅途 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:59

    To check for positive integer use:

    $i = $user_input_value;
    if (is_int($i) && $i > 0) {
      return true; //or any other instructions 
    }
    

    OR

    $i = $user_input_value;
    if (!is_int($i) || $i < 1) {
      return false; //or any other instructions 
    }
    

    Use the one that fits your purpose as they are the same. The following examples demonstrate the difference between is_numeric() and is_int():

    is_numeric(0);     // returns true
    is_numeric(7);     // returns true
    is_numeric(-7);    // returns true
    is_numeric(7.2);   // returns true
    is_numeric("7");   // returns true
    is_numeric("-7");  // returns true
    is_numeric("7.2"); // returns true
    is_numeric("abc"); // returns false
    
    is_int(0);     // returns true
    is_int(7);     // returns true
    is_int(-7);    // returns true
    is_int(7.2);   // returns false
    is_int("7");   // returns false
    is_int("-7");  // returns false
    is_int("7.2"); // returns false
    is_int("abc"); // returns false
    

提交回复
热议问题