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

4
  • 3
    possible duplicate of 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. Commented Mar 25, 2011 at 11:26
  • Implementations of json_encode are available for download, so maybe check them out and customize them? Here's one: boutell.com/scripts/jsonwrapper.html Commented Mar 25, 2011 at 11:27
  • @Pekka I need to be able to send javascript functions from the php file Commented Mar 25, 2011 at 11:28
  • not sure what you mean by that, but isn't that possible by wrapping some Javascript around a json_encode result? Commented Mar 25, 2011 at 11:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Thank you for your comment. I improved my answer with those cases.
if keys like "080" this will wrong. Example array('0'=>1, '08'=>2);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.