BonJon
BonJon

Reputation: 799

How to check if the variable is an object or an array

I am trying to check if the passed variable is an object or an array in php.

I have something like

if(is_object($product>item)) {
     if(isset($product->item->ArrayOfImage->path)) {
          $img = $product->item->ArrayOfImage->path
     }else{
          unset($img);
     }
}else{
    if(isset($product->item[$i]->ArrayOfImage->path)){  //$i is the index from a for loop
        $img = $product->item[$i]->ArrayOfImage->path
    }else{
        unset($img);
    }
}

The above codes will check whether $product->item is an object or not, if not, it treats it as array. It will also check if the value is set. I do feel like I could refactor it but not sure where to begin. Can someone help me out on this?

Upvotes: 0

Views: 225

Answers (1)

Alexey
Alexey

Reputation: 144

You can use a php built-in function gettype to detect the type of the variables:

string gettype ( mixed $var );

or you can use the is_object or is_array functions to check the variable type:

bool is_array ( mixed $var )
bool is_object ( mixed $var )

Upvotes: 1

Related Questions