为什么我总是0?

时间:2014-12-04 13:24:49

标签: php

我向file.php发送了一个请求,其中包含以下网址:file.php?number=2

file.php:

$number = 0;
if (isset($_GET['number'])) {
    $temp_var = $_GET['number']; // 2
    if (ctype_digit($temp_var)) {
        $number = (int)$temp_var; // 2
    }
}   
print $number; // 0

作为回应,我得到0(零)。为什么呢?

3 个答案:

答案 0 :(得分:7)

问题在于ctype_digit()

查看此示例

<?php

$numeric_string = '42';
$integer        = 42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 is the * character)

is_numeric($numeric_string);   // true
is_numeric($integer);          // true
?>

ctype_digit($integer); // false (ASCII 42 is the * character)在您的情况下也会发生这种情况,因为2是不同非数字字符的ASCII值,if()在您的情况下返回false。

如果你想检查字符串或数字是否实际上是一个int,你应该使用is_numeric()

您的代码将变为:

$number = 0;
if (isset($_GET['number'])) {
    $temp_var = $_GET['number']; // 2
    if (is_numeric($temp_var)) {
        $number = (int)$temp_var; // 2
    }
}   
print $number; // 2

手动注意ctype_digit()

此函数需要一个字符串才有用,因此例如传入一个整数可能不会返回预期的结果。但是,请注意HTML表单将导致数字字符串而不是整数。另请参阅手册的“类型”部分。

如果提供了介于-128和255之间的整数,则将其解释为单个字符的ASCII值(为了允许扩展ASCII范围内的字符,负值添加了256个)。任何其他整数都被解释为包含整数的十进制数字的字符串。

PLUS:

如果有人真的绝对必须使用ctype_digit(),出于安全原因,您可以使用:

ctype_digit((string) $value);

这样,你将始终确保$value是一个字符串,如果它只由数字字符组成,那么ctype_digit将评估为true;)

答案 1 :(得分:1)

是否定义了$fid

if (ctype_digit($fid)) {

你的意思是说:

if (ctype_digit($temp_var)) {

您传递的错误参数$fid未定义。$fid未设置,因此条件为false且未进入if (ctype_digit($fid)) {},因此结果显示您最初定义$number

这就是为什么你总是得到0

修改

我的回答是基于问题的先前版本。

问题海报改变了问题的内容。

我认为,如果某个机构发现我们的答案无关紧要,那不是我们的错误。

答案 2 :(得分:0)

尝试:

$number = 0;
if (isset($_GET['number'])) {
  if (is_numeric($_GET['number'])) {
    $number = (int)$_GET['number'];
  }
}   
print $number; 

按照上面的回答编辑使用is_numeric - 更好的主意