0

I need check if a specific Array is keyed or indexed. For instance:

// Key defined array
array('data-test' => true, 'data-object' => false);

// Indexed array
array('hello', 'world');

I can easily do a foreach with the array keys to check if all is integer. But exists a correct way to check it? A built-in PHP function?

POSSIBLE SOLUTION

// function is_array_index($array_test);
//    $array_test = array('data-test' => true, 'data-object' => false);

foreach(array_keys($array_test) as $array_key) {
    if(!is_numeric($array_key)) {
        return false;
    }
}

return true;
G-Nugget
  • 8,666
  • 1
  • 24
  • 31
David Rodrigues
  • 12,041
  • 16
  • 62
  • 90

4 Answers4

2
function is_indexed($arr) {
  return (bool) count( array_filter( array_keys($arr), 'is_string') );
}
1

this is from php.net function.is-array:

function is_assoc($array) {
    return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
}
bitWorking
  • 12,485
  • 1
  • 32
  • 38
1

The function

function isAssoc($arr)
{
    return array_keys($arr) !== range(0, count($arr) - 1);
}

should work.

James Coyle
  • 9,922
  • 1
  • 40
  • 48
0

You could check for the key [0]:

$arr_str = array('data-test' => true, 'data-object' => false);

$arr_idx = array('hello', 'world');

if(isset($arr_str[0])){ echo 'index'; } else { echo 'string'; }

echo "\n";

if(isset($arr_idx[0])){ echo 'index'; } else { echo 'string'; }

Example: http://codepad.org/bxCum7fU

BenOfTheNorth
  • 2,904
  • 1
  • 20
  • 46