2013-03-04 109 views
0

我需要检查一个特定的数组是否为或索引。例如:检查一个数组是否是索引数组

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

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

我可以很容易做到与阵列密钥的foreach,检查所有的整数。但存在一个正确的方法来检查它?一个内置的PHP函数?

可能的解决方案

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

回答

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

你可以检查为重点[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'; } 

实施例:http://codepad.org/bxCum7fU

1

功能

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

应该工作。

相关问题