我有简单的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;
}
}
}
?>
答案 0 :(得分: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";
}
}
?>