我希望能够将数组传递给函数,并使函数的行为有所不同,具体取决于它是"列表"样式数组还是"散列"样式数组.例如:
myfunc(array("One", "Two", "Three")); // works
myfunc(array(1=>"One", 2=>"Two", 3=>"Three")); also works, but understands it's a hash
Run Code Online (Sandbox Code Playgroud)
可能输出如下内容:
One, Two, Three
1=One, 2=Two, 3=Three
Run Code Online (Sandbox Code Playgroud)
即:当函数"检测到"它被传递的是散列而不是数组时,函数会执行不同的操作.你能说我来自Perl背景,其中%哈希是@arrays的不同引用吗?
我相信我的例子非常重要,因为我们不能只测试密钥是否为数字,因为你很可能在哈希中使用数字键.
我特别希望避免使用混乱的构造 myfunc(array(array(1=>"One"), array(2=>"Two"), array(3=>"Three")))
小智 38
从kohana框架中拉出来.
public static function is_assoc(array $array)
{
// Keys of the array
$keys = array_keys($array);
// If the array keys of the keys match the keys, then the array must
// not be associative (e.g. the keys array looked like {0:0, 1:1...}).
return array_keys($keys) !== $keys;
}
Run Code Online (Sandbox Code Playgroud)
Hus*_*ard 14
该基准提供了3种方法.
这是一个摘要,从最快到最慢排序.有关更多信息,请在此处阅读完整的基准.
1.使用array_values()
function($array) {
return (array_values($array) !== $array);
}
Run Code Online (Sandbox Code Playgroud)
2.使用array_keys()
function($array){
$array = array_keys($array); return ($array !== array_keys($array));
}
Run Code Online (Sandbox Code Playgroud)
3.使用array_filter()
function($array){
return count(array_filter(array_keys($array), 'is_string')) > 0;
}
Run Code Online (Sandbox Code Playgroud)
从技术上讲,PHP将所有数组视为哈希值,因此没有一种确切的方法可以做到这一点.我相信你最好的选择是:
if (array_keys($array) === range(0, count($array) - 1)) {
//it is a hash
}
Run Code Online (Sandbox Code Playgroud)