PHP – Determine Whether a Variable is an Object or an Array

This can be done easily in PHP. The language provides 2 functions which are useful in this case

is_object can detect if a variable is an object. It returns true if the given variable is an object.

$var = new stdClass();
if(is_object($var)){
  echo "Object";
} else {
  echo "Not an object";
}

is_array checks whether a variable is an array or not. It returns true if the given variable is an array, otherwise it returns false.

$var = array(0, 1);
if (is_array($var))
 echo 'This is an array....';
else
 echo 'This is not an array....';

PHP Readable var_dump is a small tool which can format display of an array or an object. It is not perfect but it can still show a nice output.

Leave a Reply

Your email address will not be published. Required fields are marked *