War Coder
War Coder

Reputation: 464

PHP: Getting array type

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?

Upvotes: 2

Views: 7961

Answers (5)

grantwparks
grantwparks

Reputation: 1153

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))

Upvotes: 14

Bryan Campbell
Bryan Campbell

Reputation:

function is_associative_array($array) {
    return (is_array($array) && !is_numeric(implode("", array_keys($array))));
}

Testing the keys works well.

Upvotes: 2

cletus
cletus

Reputation: 625427

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.

Upvotes: 1

Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53606

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

Upvotes: 8

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74272

Check out the discussions at is_array.

Upvotes: 1

Related Questions