Check if variable is a number and positive integer in PHP?

后端 未结 6 1398
甜味超标
甜味超标 2021-01-24 06:11

For example, say:


How do I check if variable

相关标签:
6条回答
  • 2021-01-24 06:42

    You can use is_numeric to check if a var is a number. You also have is_int. To test if it's positive juste do something like if (var > 0).

    0 讨论(0)
  • 2021-01-24 06:48

    You can do it like this:-

    if( is_int( $_GET['id'] ) && $_GET['id'] > 0 ) {
    
       //your stuff here
    
    }
    
    0 讨论(0)
  • 2021-01-24 06:55

    is_int is only for type detection. And request parameters are string by default. So it won't work. http://php.net/is_int

    A type independent working solution:

    if(preg_match('/^\d+$/D',$post_id) && ($post_id>0)){
       print "Positive integer!";
    }
    
    0 讨论(0)
  • 2021-01-24 07:00

    To check if a string input is a positive integer, i always use the function ctype_digit. This is much easier to understand and faster than a regular expression.

    if (isset($_GET['p']) && ctype_digit($_GET['p']))
    {
      // the get input contains a positive number and is safe
    }
    
    0 讨论(0)
  • 2021-01-24 07:00

    use ctype_digit but, for a positive number, you need to add the "> 0" check

    if (isset($_GET['p']) && ctype_digit($_GET['p']) && ($_GET['p'] > 0))
    {
      // the get input contains a positive number and is safe
    }
    

    in general, use ctype_digit in this way

    if (ctype_digit((string)$var))
    

    to prevent errors

    0 讨论(0)
  • 2021-01-24 07:06

    positive integer and greater that 0

    if(is_int($post_id) && $post_id > 0) {/* your code here */}
    
    0 讨论(0)
提交回复
热议问题