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

这一生的挚爱 提交于 2019-12-20 05:15:06

问题


For example, say:

<?php

    // Grab the ID from URL, e.g. example.com/?p=123
    $post_id = $_GET['p'];

?>

How do I check if variable $post_id is a number, and a positive integer at that (i.e. 0-9, not a floating point number, fraction, or a negative number)?

EDIT: Can't use is_int 'cause $_GET returns a string. Think I need to use intval() or ctype_digit(), with the latter seeming more appropriate. For example:

if( ctype_digit( $post_id ) ) { ... }

回答1:


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
}



回答2:


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!";
}



回答3:


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




回答4:


You can do it like this:-

if( is_int( $_GET['id'] ) && $_GET['id'] > 0 ) {

   //your stuff here

}



回答5:


positive integer and greater that 0

if(is_int($post_id) && $post_id > 0) {/* your code here */}



回答6:


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).



来源:https://stackoverflow.com/questions/19333292/check-if-variable-is-a-number-and-positive-integer-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!