1

I am having a little problem, I could not understand how count function works, it I instaciate an array and fill it with 4 integers, my count function return 4 obviously, but I didnt get some example.

Here is the code :

$a = $food = array('1' => "c",1 => "A",
'2' => "D"
);

echo count($a);

The message I get is 2, but it is 3 elements, no ? So I thought, that maybe because the string key ( 1 in my case ) has to one and only one in an array even if the types of keys are different ? I am right ? It is like writing code like this :

 $a[1] = "c";
 $a[1] = "A";

I added something to my array :

$a = $food = array('1' => "c",1 => "A", 'C', 
'2' => "D"
);

echo count($a); 

And I still get 2 instead of 3 if my explanation above was right!

Can you explain to me how count works exactly ? Thank you for your help

TaouBen
  • 1,165
  • 1
  • 15
  • 41
  • 2
    it's quite simple your array uses the same key 2x, keys must be unique so the first instance of key 1 is over written by the second `array('1' => "c",1 => "A",'2' => "D");` Your array really is this `array(1 => "A",'2' => "D");` Note that `'1'` is the same as `1` because of PHP's loose typing. And, as you can see the count of `2` is then what one would expect to get. – ArtisticPhoenix Dec 26 '18 at 23:11
  • 1
    Flagging for reopening because I don't think this is really a duplicate as indicated as the linked answer does not explain the behaviour seen with the *second* example. It's like the ppl voting to close only read the question halfway before deciding they ha a basis for being unhelpful. – Adam Cameron Dec 27 '18 at 09:14

0 Answers0