Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Count function with Associative Array

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);
like image 740
Parampal Pooni Avatar asked Sep 28 '11 11:09

Parampal Pooni


People also ask

How do I count items in an array PHP?

You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.

How do you count the number of keys in an array?

keys() method and the length property are used to count the number of keys in an object. The Object. keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"] . The length property returns the length of the array.

What is the use of count () function in PHP?

The count() function returns the number of elements in an array.

How do you count elements in an array?

//Number of elements present in an array can be calculated as follows. int length = sizeof(arr)/sizeof(arr[0]); printf("Number of elements present in given array: %d", length);


1 Answers

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.

like image 171
Gordon Avatar answered Sep 25 '22 23:09

Gordon