l-x.github.io

Determine the Type of a PHP Array

| Comments

PHP’s arrays are a mix of dictionaries and lists (i. e. in Python).

Sometimes you have to determine if an array is a list:

1
array('foo', 'bar', 'baz');

or a dictionary:

1
2
3
4
array(
  'foo'   => 'bar',
  'herp'  => 'derp'
);

Unfortunately PHP has no built-in method to do so. One of the good solutions I’ve ran across is to use the array_filter() on the array’s keys to determine if they’re all integers:

1
2
3
function is_array_indexed($array) {
  return count(array_filter(array_keys($array), 'is_int') == count($array);
}

This function simply compares the number of items which keys are integers to the number of all items in the array. If both are equal the array is indexed.

As a variation one could use is_string() instead of is_int():

1
2
3
function is_array_indexed($array) {
  return count(array_filter(array_keys($array), 'is_string') == 0;
}

The advantage of this variant is that no additional count($array) is required, so it should be slightly faster than the first variant.

Both examples can easily be modified to return the type of the array:

Comments