在php中,如何检查变量是字符串还是数字?
我正在使用mysql进行count()
,并想知道输出是字符串还是数字。
我知道php中的is_numeric()和其他函数,但是有什么东西,如果提供了值,如果值是数字或字符串,它将回显吗?
答案 0 :(得分:3)
尝试使用gettype
功能。
gettype('foo'); // string
gettype(1.23); // double
gettype(155); // integer
答案 1 :(得分:0)
问题在于,如果您使用框架或数据抽象层,并且这会处理数据库的输出,通常数据类型在此过程中丢失,一切都变为字符串。 在这种情况下,is_numeric是最明显的!!!
答案 2 :(得分:0)
简答:
使用:
echo $gettype($YourValueFromDB);
在您的情况下将输出:
string
OR
if(is_int($YourValueFromDB))
{
echo 'we have an integer type!';
}
elseif(is_string($YourValueFromDB))
{
echo 'we have a string type!';
}
else
{
echo 'Not sure: '.gettype($YourValueFromDB);
}
答案很长:
MySQL使用此查询生成一个数字值:
select count(*) as total from table
// can range from 0 - infinity (or exhausted memory limit, whichever comes first)
// for this post, pretend this count() returns a 9
当这些数据传回PHP时,由于PHP非常宽松的类型转换,它会自动转换为字符串。
运行此:
var_dump($row);
会产生这样的东西:
array
'total' => string '9' (length=1)
表示您正在使用文字字符串,但它的值是一个数字,因此if($row['total'] > 1){ }
之类的内容会在花括号中出现而没有问题。