检查变量是否是 PHP 中的数字和正整数


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

例如,说:

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

如何检查变量 $post_id 是否是一个数字,并且是一个正整数(即 0-9,而不是浮点数、分数或负数(?

编辑:不能使用is_int'原因$_GET返回一个字符串。认为我需要使用intval()ctype_digit(),后者似乎更合适。例如:

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

要检查字符串输入是否为正整数,我总是使用 ctype_digit 函数。这比正则表达式更容易理解且速度更快。

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

这样做:-

if( is_int( $_GET['id'] ) && $_GET['id'] > 0 ) {
   //your stuff here
}

is_int仅用于类型检测。默认情况下,请求参数为字符串。所以它行不通。http://php.net/is_int

与类型无关的工作解决方案:

if(preg_match('/^'d+$/D',$post_id) && ($post_id>0)){
   print "Positive integer!";
}

使用ctype_digit但是,对于正数,您需要添加"> 0"检查

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

通常,以这种方式使用ctype_digit

if (ctype_digit((string)$var))

防止错误

正整数且大于 0

if(is_int($post_id) && $post_id > 0) {/* your code here */}
您可以使用

is_numeric来检查变量是否为数字。你也有is_int。要测试它是否是积极的,请执行类似 if (var> 0( 的操作。