Walking on water and developing software from a specification are easy if both are frozen.
Edward V Berard

PHP Code: Checking Associative Array

There are two kinds of array in PHP: numerical array and associative array. Sometimes, we need to know whether a given array is numerical or associative. So, how to do it, since PHP only has is_array()? Well, recently I found someone asking this kind of problem in stackoverflow and I answered it here. So this is the answer I proposed (I love one-liner :|):

function is_assoc($array) {
  return is_array($array) && (bool)count(array_filter(array_keys($array), 'is_string'));
}

Note: I added the “is_array($array)”, it wasn’t there in the stackoverflow answer.

The above function will return true if $array is an associative array (have at least one string key). To explain the code, let’s rewrite it this way:

function is_assoc($array) {
  if (!is_array($array)) return false;
  $keys = array_keys($array);
  $filtered = array_filter($keys, 'is_string');
  $count = count($filtered);
  return $count > 0;
}

I guess the above rewritten code explains itself. The concept is to count how many string keys does $array has. This is done using array_filter() and array_keys(). If there is more than one element in $filtered, that means $array has more than one string keys thus $array is an associative array, otherwise it is not.

February 1st, 2011 PHP Tags: , , 0 Comment 409 views