PHP计数功能与关联数组

Par*_*oni 10 php associative-array count

有人可以向我解释一下count函数如何与下面的数组一起工作吗?

我的想法是输出4的以下代码,因为那里有4个元素:

$a = array 
(
  "1" => "A",
   1=> "B",
   "C",
   2 =>"D"
);

echo count($a);
Run Code Online (Sandbox Code Playgroud)

Gor*_*don 28

count完全按照您的预期工作,例如,它计算数组(或对象)中的所有元素.但是你对包含四个元素的数组的假设是错误的:

  • "1"等于1,因此1 => "B"将覆盖"1" => "A".
  • 因为你定义了1,下一个数字索引将是2,例如"C" 2 => "C"
  • 你指定的时候2 => "D"覆盖了"C".

因此,您的数组将只包含1 => "B",2 => "D"这就是为什么count给出2.您可以通过执行来验证这是真的print_r($a).这会给

Array
(
    [1] => B
    [2] => D
)
Run Code Online (Sandbox Code Playgroud)

请再次浏览http://www.php.net/manual/en/language.types.array.php.


San*_*sal 7

您可以使用此示例来了解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

?>
Run Code Online (Sandbox Code Playgroud)

资源