嗨,我有一个关于数组的简单问题。
我正在尝试使用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);
}