That's because the 'index 0' data has key 0. In PHP, 0
(number zero), '0'
(string zero), and ''
(empty string) are all equivalent - they can get typecast to each other. If you'd simply done print_r($test_array)
, you'd get
Array
(
[string_index] => data in string index
[0] => data in index 0
[1] => data in index 1
[2] => data in index 2
)
The other option would have been to use the strict inequality test (!==
) which compares value AND type. In that case, 0 !== 'string index'
evaluates to true and everything works as expected.
Comment followup:
if you'd change the inside of your loop to this:
echo "key: $key (", gettype($key), ") val: $val (", gettype($val), ")\n";
if($key != 'string_index') {
echo "$key != 'string_index'\n";
} else {
echo "$key == 'string_index'\n";
}
You'll get:
key: string_index (string) val: data in string index (string)
string_index == 'string_index'
key: 0 (integer) val: data in index 0 (string)
0 == 'string_index'
key: 1 (integer) val: data in index 1 (string)
1 != 'string_index'
key: 2 (integer) val: data in index 2 (string)
2 != 'string_index'
As you can see, they're all there - it's your comparison that was failing you, because you didn't take PHP's typecasting/conversion rules into account.