2013-03-04 107 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); 
} 

應該工作。

相關問題