【问题标题】:Read user input and check data type读取用户输入并检查数据类型
【发布时间】:2018-10-03 20:45:51
【问题描述】:

我有一个简单的 PHP 脚本:

<?php
$input = readline();

echo gettype($input);
?>

它从控制台读取用户输入。我想要实现的是获得正确的数据类型。目前 $input 是字符串类型。

我需要这样的东西:

Input    Output
 5       Integer
2.5      float
true     Boolean

我不知道该怎么做。谢谢。

编辑:感谢@bcperth 的回答,我实现了这个工作代码:

<?php
 while(true) {
 $input = readline();
 if($input == "END") return ;
  if(is_numeric($input)) {
      $sum = 0;
      $sum += $input;
       switch(gettype($sum)) {
           case "integer": $type = "integer"; break;
           case "double": $type = "floating point"; break;
       }
       echo "$input is $type type" . PHP_EOL;
  }
  if(strlen($input) == 1 && !is_numeric($input)) {
      echo "$input is character type" . PHP_EOL;
  } else if(strlen($input) > 1 && !is_numeric($input) && strtolower($input) != "true" && strtolower($input) != "false") {
      echo "$input is string type" . PHP_EOL;
  }  if(strtolower($input) == "true" || strtolower($input) == "false") {
      echo "$input is boolean type" . PHP_EOL;
  }
 }
?>

也试过filter_var,效果很好:

<?php
while(true) {
    $input = readline();
    if($input == "END") return;
      if(!empty($input)) {
        if(filter_var($input, FILTER_VALIDATE_INT) || filter_var($input, FILTER_VALIDATE_INT) === 0) {
        echo "$input is integer type" . PHP_EOL;
        } else if(filter_var($input, FILTER_VALIDATE_FLOAT) || filter_var($input, FILTER_VALIDATE_FLOAT) === 0.0) {
        echo "$input is floating point type" . PHP_EOL;
        } else if(filter_var($input, FILTER_VALIDATE_BOOLEAN) || strtolower($input) == "false") {
        echo "$input is boolean type" . PHP_EOL;
        } else if(strlen($input) == 1) {
        echo "$input is character type" . PHP_EOL;
        } else {
        echo "$input is string type" . PHP_EOL;
        }
      }
}

?>

【问题讨论】:

  • 用户输入总是一个字符串。您可以使用is_numeric() 检查此字符串是否包含数字,但这不区分整数和浮点数。
  • ctype_digit() 可能也值得一看,它会为整数返回 true,为浮点数返回 false,因为浮点数将包含小数分隔符。另一方面,所有整数也是有效的浮点数...
  • @KarstenKoop ctype_digit() 不适用于负数
  • 远离目标的简单搜索 :: stackoverflow.com/questions/2690654/…
  • @VayuDev bcperth 给出的答案比你所链接的问题中的那个可怜的答案要有效得多

标签: php


【解决方案1】:

对于简单类型,您需要采用以下几种策略。

  1. 使用 is_numeric() 测试是否为数字。
  2. 如果是数字,则将其加到零并 gettype() 结果
  3. 如果不是数字,则比较“真”和“假”
  4. 如果不是“true”或“false”,则为字符串

这是一个展示如何去做的工作开始。

<?php
$input = readline();

if (is_numeric($input)){
    $sum =0;
    $sum += $input;
    echo gettype($sum);
}
else {
    if ($input== "true" or $input == "false"){
        echo "boolean";
    }
    else {
        echo "string";
    }
}

?>

【讨论】:

  • 谢谢,我在您的“逻辑”帮助下编辑了我的答案,现在它按我的预期工作。 :)
猜你喜欢
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多