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

久未见 提交于 2019-12-02 06:14:53

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
}

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

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

nurakantech

You can do it like this:-

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

   //your stuff here

}
vaibhavmande

positive integer and greater that 0

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

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

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