代码之家  ›  专栏  ›  技术社区  ›  AnTrakS

读取用户输入并检查数据类型

php
  •  3
  • AnTrakS  · 技术社区  · 7 年前

    我有一个简单的PHP脚本:

    <?php
    $input = readline();
    
    echo gettype($input);
    ?>
    

    我需要这样的东西:

    Input    Output
     5       Integer
    2.5      float
    true     Boolean
    

    我不知道怎么做。谢谢。

    感谢@bcperth answer,我实现了以下工作代码:

    <?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;
            }
          }
    }
    
    ?>
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   bcperth    7 年前

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

    1. 测试numeric using是否为\u numeric()。
    2. 如果是数字,则将其添加到0并获取结果的gettype()
    3. 如果不是数字,则比较“真”和“假”

    这是一个工作的开始,说明如何去做。

    <?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";
        }
    }
    
    ?>
    
    推荐文章