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'];

 foreach($test as $t){
   echo $t;
   echo $test;



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 functiongettype() You can refine the results if $type is 'Object' using the functionget_class()

$type = gettype($var);

// get class name for objects if so desired
if($type === 'object') {
    $type = get_class($var);

People are also looking for solutions to the problem: Can not format date as per requirement using PHP


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.