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);
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.
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.
The count() function returns the number of 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);
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 => "B"
will overwrite "1" => "A"
. 2 => "C"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With