PHP计数函数与关联数组 [英] PHP Count function with Associative Array
问题描述
有人可以向我解释count函数如何与下面的数组一起使用?
Could someone please explain to me how the count function works with arrays like the one below?
我的想法是以下代码输出4,因为有4个元素:
My thought would be the following code to output 4, cause there are 4 elements there:
$a = array
(
"1" => "A",
1=> "B",
"C",
2 =>"D"
);
echo count($a);
推荐答案
$ c>工作正如你所期望的,eg它计算数组(或对象)中的所有元素。但是你对包含四个元素的数组的假设是错误的:
count
works exactly as you would expect, e.g. it counts all the elements in an array (or object). But your assumption about the array containing four elements is wrong:
- 1等于1,因此
1 => B
将覆盖1=> A
。 - 因为您定义了1,下一个数字索引将为2,例如C是
2 =>当您分配
2 =>时,C
< D您覆盖了C。
- "1" is equal to 1, so
1 => "B"
will overwrite"1" => "A"
. - because you defined 1, the next numeric index will be 2, e.g. "C" is
2 => "C"
- when you assigned
2 => "D"
you overwrote "C".
因此,您的数组将只包含 1 => B
和 2 => D
这就是为什么 count
给出2.你可以通过执行 print_r($ a) / code>。这将给予
So your array will only contain 1 => "B"
and 2 => "D"
and that's why count
gives 2. You can verify this is true by doing print_r($a)
. This will give
Array
(
[1] => B
[2] => D
)
请通过http://www.php.net/manual/en/language.types.array.php 。
这篇关于PHP计数函数与关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!