2

Is there a php function that someone can use to automatically detect if an array is an associative or not, apart from explictly checking the array keys?

hakre
  • 193,403
  • 52
  • 435
  • 836
War Coder
  • 454
  • 1
  • 7
  • 24
  • 2
    I sense something wrong in your design. Why would you want to do this? – Randell Jul 26 '09 at 05:13
  • It's not an uncommon need, especially when writing more generic, non application-specific code. – grantwparks Apr 02 '12 at 06:36
  • possible duplicate of [PHP Arrays: A good way to check if an array is associative or sequential?](http://stackoverflow.com/questions/173400/php-arrays-a-good-way-to-check-if-an-array-is-associative-or-sequential) – Gordon Jun 19 '12 at 17:57

5 Answers5

15

My short answer: YES

Quicker and easier, IF you make the assumption that a "non-associative array" is indexed starting at 0:

if ($original_array == array_values($original_array))
grantwparks
  • 1,124
  • 9
  • 13
  • 1
    I feel I have to continue because other answers that take longer are being voted up. One does not have to examine the keys. array_values() returns an integer-indexed array, thus if one compares the array in question with its array_values() and they are equal, the original array is a 0 based, integer indexed array. It is the shortest, slickest way. Try it out. – grantwparks Jul 25 '09 at 14:14
  • I agree, arrays that are not indexed *continuously starting at `0`* should be considered associative, since they can't be traversed reliably with the typical `for ($x++)` pattern. Hence this test is probably the best to use. It becomes sort of a philosophical debate though, as PHP arrays simply aren't one or the other. :) – deceze Jul 26 '09 at 05:51
  • 1
    I was just trying to pass on the quickest/slickest way I found to determine if the indices are 0 thru N without any kind of explicit inspection of the keys.

    I _love_ PHP arrays.

    – grantwparks Jul 26 '09 at 13:40
9

quoted from the official site:

The indexed and associative array types are the same type in PHP,

So the best solution I can think of is running on all the keys, or using array_keys,implode,is_numeric

Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278
2
function is_associative_array($array) {
    return (is_array($array) && !is_numeric(implode("", array_keys($array))));
}

Testing the keys works well.

1

Check out the discussions at is_array.

Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
1

Short answer: no.

Long answer: Associative and indexed arrays are the same type in PHP. Indexed arrays are a subset of associative arrays where:

  • The keys are only integers;
  • They range from 0 to N-1 where N is the size of the array.

You can try and detect that if you want by using array_keys(), a sort and comparison with a range() result.

cletus
  • 616,129
  • 168
  • 910
  • 942