php检查变量是否为整数

标签 php html validation

有更好的方法吗?

if( $_POST['id'] != (integer)$_POST['id'] )
    echo 'not a integer';

我试过了

if( !is_int($_POST['id']) )

但是 is_int() 由于某种原因不起作用。

我的表单是这样的

<form method="post">
   <input type="text" name="id">
</form>

我研究过is_int(),好像如果

is_int('23'); // would return false (not what I want)
is_int(23);   // would return true

我也试过 is_numeric()

is_numeric('23'); // return true
is_numeric(23); // return true
is_numeric('23.3'); // also returns true (not what I want)

似乎唯一的办法是: [这是一种不好的方法,不要这样做,见下面的注释]

if( '23' == (integer)'23' ) // return true
if( 23 == (integer)23 ) // return true
if( 23.3 == (integer)23.3 ) // return false
if( '23.3' == (integer)'23.3') // return false

但是有没有实现上述功能的功能呢?


澄清一下,我想要以下结果

23     // return true
'23'   // return true
22.3   // return false
'23.3' // return false

注意:我刚刚发现我之前提出的解决方案将对所有字符串返回 true。 (感谢 redreggae)

$var = 'hello';
if( $var != (integer)$var )
    echo 'not a integer';

// will return true! So this doesn't work either.

这不是 Checking if a variable is an integer in PHP 的副本,因为我对整数的要求/定义与那里不同。

最佳答案

试试 ctype_digit

if (!ctype_digit($_POST['id'])) {
    // contains non numeric characters
}

注意:它只适用于 string 类型。因此,您必须将普通变量转换为 string:

$var = 42;
$is_digit = ctype_digit((string)$var);

另请注意:它不适用于负整数。如果你需要这个,你将不得不使用正则表达式。我找到了 this例如:

编辑:感谢 LajosVeres,我添加了 D 修饰符。所以 123\n 无效。

if (preg_match("/^-?[1-9][0-9]*$/D", $_POST['id'])) {
    echo 'String is a positive or negative integer.';
}

更多:使用强制转换的简单测试将不起作用,因为 "php"== 0 是 true 而 "0"=== 0 是 false! 见 types comparisons table为此。

$var = 'php';
var_dump($var != (int)$var); // false

$var = '0';
var_dump($var !== (int)$var); // true

关于php检查变量是否为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19235746/

相关文章:

php - 相当于 glob() ,它可以使用数组而不是文件系统

php - 基于自定义字段的每个购物车项目的 WooCommerce 自定义数量输入步骤

php - 将 JSON 解码为 PHP 数组,删除相同的条目并编码回 PHP

javascript - 从屏幕外 Canvas 上绘制的图像像素采样颜色时出现问题

php - 调用字符串上的成员函数 all()(查看 :

php - email@domain 是有效的电子邮件地址吗

php - 如何配置本地 web 服务器,使其在一个 php 版本和另一个 php 版本之间切换

html - Sprite 导航上的下拉菜单

javascript - Jquery/Javascript onclick 事件到 html 打开选择标签

perl - 我在哪里可以找到一些简单的 Perl W3C Validator API 信息?