PHP Count 函数与关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7582443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Count function with Associative Array
提问by Parampal Pooni
Could someone please explain to me how the count function works with arrays like the one below?
有人可以向我解释一下 count 函数是如何处理如下数组的吗?
My thought would be the following code to output 4, cause there are 4 elements there:
我的想法是以下代码输出 4,因为那里有 4 个元素:
$a = array
(
"1" => "A",
1=> "B",
"C",
2 =>"D"
);
echo count($a);
回答by Gordon
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:
count
完全按照您的预期工作,例如,它计算数组(或对象)中的所有元素。但是您对包含四个元素的数组的假设是错误的:
- "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" 等于 1,所以
1 => "B"
会覆盖"1" => "A"
. - 因为您定义了 1,所以下一个数字索引将是 2,例如“C”是
2 => "C"
- 当您分配时,
2 => "D"
您覆盖了“C”。
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
所以你的数组将只包含1 => "B"
and2 => "D"
这就是为什么count
给出 2. 你可以通过执行print_r($a)
. 这会给
Array
(
[1] => B
[2] => D
)
Please go through http://www.php.net/manual/en/language.types.array.phpagain.
回答by Sandeep Bansal
You can use this example to understand how count works with recursive arrays
您可以使用此示例来了解 count 如何与递归数组一起使用
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard', 'pea'));
// recursive count
echo count($food, COUNT_RECURSIVE); // output 8
// normal count
echo count($food); // output 2
?>
回答by piddl0r
The array you have created only has two elements in it hence the count returning 2. You are overwriting elements, to see whats in your array use :
您创建的数组中只有两个元素,因此计数返回 2。您正在覆盖元素,以查看数组中的内容使用:
print_r($a);