AnTrakS
AnTrakS

Reputation: 743

Read user input and check data type

I've simple PHP script:

<?php
$input = readline();

echo gettype($input);
?>

It reads user input from the console. What I am trying to achieve is to get properly data type. At the moment $input is string type.

I need something like this:

Input    Output
 5       Integer
2.5      float
true     Boolean

I can't get any idea how to do it. Thanks.

EDIT: Thanks to @bcperth answer, I achieve this working code:

<?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;
  }
 }
?>

Also tried with filter_var, working well:

<?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;
        }
      }
}

?>

Upvotes: 3

Views: 1259

Answers (1)

bcperth
bcperth

Reputation: 2291

You would need to employ a few strategies as below for simple types.

  1. test if numeric using is_numeric().
  2. if numeric then add it to zero and gettype() the result
  3. if not numeric then compare to "true" and "false"
  4. if not "true" or "false" then its a string

Here is a working start that shows how to go about it.

<?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";
    }
}

?>

Upvotes: 3

Related Questions