开发者

Determine if a PHP array uses keys or indices [duplicate]

This question already has answers here: How to check if PHP array is associative or sequential? (59 answers) Closed 9 years ago.

How do I find out if a PHP array was built like this:

array('First', 'Second', 'Third');

Or like this:

array('first' => 'First', 'second' => 'Second', 'third' => 'Third');

开发者_运维问答???


I have these simple functions in my handy bag o' PHP tools:

function is_flat_array($ar) {
    if (!is_array($ar))
        return false;

    $keys = array_keys($ar);
    return array_keys($keys) === $keys;
}

function is_hash($ar) { 
   if (!is_array($ar))
       return false;

   $keys = array_keys($ar);
   return array_keys($keys) !== $keys;
}

I've never tested its performance on large arrays. I mostly use it on arrays with 10 or fewer keys so it's not usually an issue. I suspect it will have better performance than comparing $keys to the generated range 0..count($array).


print_r($array);


There is no difference between

array('First', 'Second', 'Third');

and

array(0 => 'First', 1 => 'Second', 2 => 'Third');

The former just has implicit keys rather than you specifying them


programmatically, you can't. I suppose the only way to check in a case like yours would be to do something like: foreach ($myarray as $key => $value) { if ( is_numeric($key) ) { echo "the array appears to use numeric (probably a case of the first)"; } }

but this wouldn't detect the case where the array was built as $array = array(0 => "first", 1 => "second", etc);


function is_assoc($array) {
    return (is_array($array) 
       && (0 !== count(array_diff_key($array, array_keys(array_keys($array)))) 
       || count($array)==0)); // empty array is also associative
}

here's another

function is_assoc($array) {
    if ( is_array($array) && ! empty($array) ) {
        for ( $i = count($array) - 1; $i; $i-- ) {
            if ( ! array_key_exists($i, $array) ) { return true; }
        }
        return ! array_key_exists(0, $array);
    }
    return false;
}

Gleefully swiped from the is_array comments on the PHP documentation site.


That's a little tricky, especially that this form array('First', 'Second', 'Third'); implicitly lets PHP generate keys values.

I guess a valid workaround would go something like:

function array_indexed( $array )
{
    $last_k = -1;

    foreach( $array as $k => $v )
    {
        if( $k != $last_k + 1 )
        {
            return false;
        }
        $last_k++;
    }

    return true;
}


If you have php > 5.1 and are only looking for 0-based arrays, you can shrink the code to

$stringKeys = array_diff_key($a, array_values($a));
$isZeroBased = empty($stringKeys);

I Hope this will help you Jerome WAGNER


function isAssoc($arr)
{
    return $arr !== array_values($arr);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜