What one man can invent another can discover.
Sherlock Holmes

Enums in PHP?

For those of you who have known PHP and programming in general, you might have noticed that PHP has no Enum. Some people say that they need Enum so they have invented several ways to emulate Enum behavior in PHP. (The list below) Read the rest of this entry »

February 17th, 2011 PHP Tags: , , , 2 Comments 1,474 views

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