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

4 Answers 4

2
function is_indexed($arr) {
  return (bool) count( array_filter( array_keys($arr), 'is_string') );
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

The function

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

should work.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.