7

Possible Duplicate:
PHP Arrays: A good way to check if an array is associative or sequential?

Hello :)

I was wondering what is the shortest (best) way to check if an array is

a list: array('a', 'b', 'c')

or it's an associative array: array('a' => 'b', 'c' => 'd')

fyi: I need this to make a custom json_encode function

Community
  • 1
  • 1
Teneff
  • 30,564
  • 13
  • 72
  • 103
  • 3
    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) Why do you need to build a custom `json_encode` function though? Are you on a PHP version that doesn't have it yet? There are pre-made packages for that case. – Pekka Mar 25 '11 at 11:26
  • Implementations of `json_encode` are available for download, so maybe check them out and customize them? Here's one: http://www.boutell.com/scripts/jsonwrapper.html – Joost Mar 25 '11 at 11:27
  • @Pekka I need to be able to send javascript functions from the php file – Teneff Mar 25 '11 at 11:28
  • not sure what you mean by that, but isn't that possible by wrapping some Javascript around a `json_encode` result? – Pekka Mar 25 '11 at 11:48

1 Answers1

14
function is_assoc($array){
    return array_values($array)!==$array;
}

Note that it will also return TRUE if array is indexed but contains holes or doesn't start with 0, or keys aren't ordered. I usually prefer using this function because it gives best possible performance. As an alternative for these cases I prefer this (just keep in mind that it's almost 4 times slower than above):

function is_assoc($array){
    return !ctype_digit( implode('', array_keys($array)) );
}

Using ksort() as Rinuwise commented is a bit slower.

Slava
  • 2,040
  • 15
  • 15
  • 3
    Note that this doesn't work, if the array keys are not in order in the array. If this is not desired, it can be avoided by performing ksort() on the array prior the comparison. – Riimu Mar 25 '11 at 11:34
  • Thank you for your comment. I improved my answer with those cases. – Slava Mar 25 '11 at 11:56
  • if keys like "080" this will wrong. Example array('0'=>1, '08'=>2); – ZigZag May 10 '12 at 10:05