user1924247
user1924247

Reputation: 171

counting array with both integer and string keys

echo count(array("1" => "A", 1 => "B", "C", 2 => "D"));

This outputs 2. I've played around with it and noticed that PHP identifies both string numbers and integers the same when used as keys in an array. Seems like integers are prioritized. Also when I var_dump the array only elements containing the value "B" and "D" are displayed. I understand why "A" is not displayed but why is "C" not in the var_dump?

Upvotes: 1

Views: 159

Answers (2)

djthoms
djthoms

Reputation: 3096

It appears as though you cannot mix associative arrays and non-associative arrays together. If you add an index to C like you did for everything else, it works as expected. As for strings, if they are a valid integer then it will be casted to an int arrays.

$arr = array("0" => "A", 1 => "B", 2 => "C", 3 => "D");
// However, if you do:
$array = array(
    "0" => "A",
    1   => "B",
    "2" => array(1, 2, 3)
);

It shows up like you would expect in a var_dump array(3) { [0]=> string(1) "A" [1]=> string(1) "B" [2]=> array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } }

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

Your array is basically being built as follows:

Key "1" is an integer-like string, treat as integer 1
Assign "A" to key 1
Assign "B" to key 1 (overwrite "A")
No explicit key, take greatest key so far and add 1 = 2
Assign "C" to key 2
Assign "D" to key 2 (overwrite "C")

Thus your resulting array is array(1=>"B",2=>"D");

Upvotes: 5

Related Questions