Determine if a PHP array uses keys or indexes

How to find out if a PHP array was built as follows:

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

Or like this:

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

???

+3
source share
8 answers

I have these simple functions in my handy PHP tool bag:

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 have never tested my performance on large arrays. I mainly use it on arrays with 10 or less keys, so this is usually not a problem. I suspect it will have better performance than comparing $ keys with the span generated 0..count($array).

+3
source
print_r($array);
0
source

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

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

,

0
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
}

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;
}

is_array PHP.

0

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

, :

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

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

    return true;
}
0

, . , , , - - :    foreach ($ myarray as $key = > $value) {       if (is_numeric ($ key)) {           echo ", , (, )";       }    }

, $array = array (0 = > "first", 1 = > "second" ..);

0

php > 5.1 0,

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

, WAGNER

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

Source: https://habr.com/ru/post/1740827/


All Articles