PHP Count function with Associative Array

那年仲夏 提交于 2019-12-12 08:26:13

问题


Could someone please explain to me how the count function works with arrays like the one below?

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);

回答1:


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" 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".

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
)

Please go through http://www.php.net/manual/en/language.types.array.php again.




回答2:


You can use this example to understand how count works with recursive arrays

<?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

?>

Source




回答3:


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 :

print_r($a);


来源:https://stackoverflow.com/questions/7582443/php-count-function-with-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!