Best way to check for positive integer (PHP)?

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

    This's my solution, hope helpful :

    if (is_numeric($i) && (intval($i) == floatval($i)) && intval($i) > 0)
       echo "positive integer";
    

    i check if string is numeric, second check to sure it's integer and third to sure it positive

    0 讨论(0)
  • 2020-12-02 18:58

    The first example is using round to verify that the input is an integer, and not a different numeric value (ie: a decimal).

    is_int will return false if passed a string. See the PHP manual examples for is_int

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-02 19:00

    I would do something like this:

    if ((int) $i > 0) {
        // this number is positive
    }
    

    The number gets typecast to a positive or negative number depending on the minus sign being at the front. Then compares the typecast number to being greater than 0 to determine if the number is positive.

    0 讨论(0)
  • 2020-12-02 19:04
    if(preg_match('/^[1-9]\d*$/',$i)) {
       //Positive and > 0
    }
    
    0 讨论(0)
  • 2020-12-02 19:08

    Laravel 4.2 Validation rule for positive number

    It takes only positive numbers including float values.

    public static $rules = array(
        'field_name' => 'required|regex:/^\d*\.?\d*$/'
    );
    

    e.g:20,2.6,06

    0 讨论(0)
提交回复
热议问题