echo count(array("1" => "A", 1 => "B", "C", 2 => "D"));
这输出2.我玩过它并注意到PHP在用作数组中的键时识别字符串数和整数相同。似乎整数是优先的。另外,当我对数组进行var_dump时,只显示包含值“B”和“D”的元素。我理解为什么“A”没有显示,但为什么“C”不在var_dump中?
答案 0 :(得分:5)
您的数组基本上按如下方式构建:
Key "1" is an integer-like string, treat as integer 1
Assign "A" to key 1
Assign "B" to key 1 (overwrite "A")
No explicit key, take greatest key so far and add 1 = 2
Assign "C" to key 2
Assign "D" to key 2 (overwrite "C")
因此,您得到的数组是array(1=>"B",2=>"D");
答案 1 :(得分:0)
看起来好像你不能将关联数组和非关联数组混合在一起。如果您像其他所有内容一样向C
添加索引,它会按预期工作。至于字符串,如果它们是一个有效的整数,那么它将被转换为int arrays。
$arr = array("0" => "A", 1 => "B", 2 => "C", 3 => "D");
// However, if you do:
$array = array(
"0" => "A",
1 => "B",
"2" => array(1, 2, 3)
);
它会像您在var_dump array(3) { [0]=> string(1) "A" [1]=> string(1) "B" [2]=> array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } }