用if语句检查变量类型


Check variable type with if statement

嗨,我有一个关于数组的简单问题。

我正在尝试使用foreach循环来响应vars。然而,有时variable不会是array我已经创建了一个if语句来检查variable类型,但我不确定这是否是最好的做法。

有更好的方法来做我需要的吗?非常感谢!

我的代码
$test = $_GET['testVar'];
if(is_array($test)){
 foreach($test as $t){
   echo $t;
 }
}else{
   echo $test;
}

is_array是检查变量是否为数组的最佳方法。所以你的代码没问题。


然而,这里有一个通用的解决方案,将适用于所有数据类型,而不仅仅是具有gettype()函数的数组如果$type是'Object',可以使用函数get_class()

来细化结果
$type = gettype($var);
// get class name for objects if so desired
if($type === 'object') {
    $type = get_class($var);
}