php 检查变量是否是PHP中的数字和正整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19333292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if variable is a number and positive integer in PHP?
提问by its_me
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)?
我如何检查变量$post_id
是否是一个数字,以及一个正整数(即 0-9,不是浮点数、分数或负数)?
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:
编辑:不能使用is_int
,因为$_GET
返回一个字符串。认为我需要使用intval()
or ctype_digit()
,后者似乎更合适。例如:
if( ctype_digit( $post_id ) ) { ... }
回答by martinstoeckli
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.
要检查字符串输入是否为正整数,我总是使用函数ctype_digit。这比正则表达式更容易理解和更快。
if (isset($_GET['p']) && ctype_digit($_GET['p']))
{
// the get input contains a positive number and is safe
}
回答by Sparviero Sughero
use ctype_digit but, for a positive number, you need to add the "> 0" check
使用 ctype_digit 但是,对于正数,您需要添加“> 0”检查
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
一般来说,以这种方式使用 ctype_digit
if (ctype_digit((string)$var))
to prevent errors
防止错误
回答by nurakantech
You can do it like this:-
你可以这样做:-
if( is_int( $_GET['id'] ) && $_GET['id'] > 0 ) {
//your stuff here
}
回答by Lajos Veres
is_int is only for type detection. And request parameters are string by default. So it won't work. http://php.net/is_int
is_int 仅用于类型检测。并且请求参数默认是字符串。所以它不会工作。http://php.net/is_int
A type independent working solution:
一个类型独立的工作解决方案:
if(preg_match('/^\d+$/D',$post_id) && ($post_id>0)){
print "Positive integer!";
}
回答by vaibhavmande
positive integer and greater that 0
大于 0 的正整数
if(is_int($post_id) && $post_id > 0) {/* your code here */}
回答by iPouf
You can use is_numericto 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).
您可以使用is_numeric来检查 var 是否为数字。你也有is_int。要测试它是否为正juste,请执行类似 if (var > 0) 的操作。