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?

3
  • 2
    I sense something wrong in your design. Why would you want to do this? Commented Jul 26, 2009 at 5:13
  • It's not an uncommon need, especially when writing more generic, non application-specific code. Commented Apr 2, 2012 at 6:36
  • possible duplicate of PHP Arrays: A good way to check if an array is associative or sequential? Commented Jun 19, 2012 at 17:57

5 Answers 5

14

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))
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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. :)
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.<p>I love PHP arrays.
8

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

1 Comment

Please see my comment below about comparing the original array to its array_values().
2
function is_associative_array($array) {
    return (is_array($array) && !is_numeric(implode("", array_keys($array))));
}

Testing the keys works well.

Comments

1

Check out the discussions at is_array.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.