18

How does the count function work with arrays, like the one below?

My thought would be that the following code outputs 4, because there are four elements there:

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

echo count($a);
2
  • Where is the code example from? It is similar to example #2, "Type casting and overwriting example" (my emphasis), in Arrays (official documentation). Commented Jun 2, 2024 at 9:24
  • The title ought to be more specific. For example, some answerers don't read past the title... Commented Jun 2, 2024 at 9:28

3 Answers 3

34

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 Arrays again.

Sign up to request clarification or add additional context in comments.

Comments

8

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

2 Comments

What is a "recursive array"? With some kind of tree structure? Or something else?
This doesn't answer the question. The gist of the question is the overwriting of items during the definition, not how the length of associative arrays is defined/computed in general.
0

The array you have created only has two elements in it, hence count returning 2. You are overwriting elements; to see what’s in your array, use:

print_r($a);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.