php - Check variable type with if statement
Hi I have a simple question regarding the array.
I am trying to useforeach
loop to echo thevars
. However, there are times that thevariable
wont' be anarray
I have created aif
statement to check thevariable
type, but I am not sure if it's the best practice doing it.
Are there any better way to do what I need? Thanks a lot!
My codes
$test = $_GET['testVar'];
if(is_array($test)){
foreach($test as $t){
echo $t;
}
}else{
echo $test;
}
Answer
Solution:
is_array
is the best way to check if a variable is an array. So your code is ok.However here comes a generic solution that will work for all data types not just arrays with the function
gettype()
You can refine the results if $type is 'Object' using the functionget_class()