开发者

How to check if array is list? [duplicate]

This question already has answers here: Closed 11 years ago.

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 assoc开发者_开发百科iative array: array('a' => 'b', 'c' => 'd')

fyi: I need this to make a custom json_encode function


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜