问题
Is there any difference between integer index and string index of PHP arrays (except of course the fact that the latter is called associative array)?
So for example, what are the differences between the following two arrays:
$intIndex[5] = "Hello";
$intIndex[6] = "World";
$intIndex[7] = "!";
And
$strIndex['5'] = "Hello";
$strIndex['6'] = "World";
$strIndex['7'] = "!";
In the first case, what happens to $intIndex[0] to $intIndex[4]?
回答1:
From the manual (emphasis mine):
The key can either be an integer or a string. The value can be of any type.
Additionally the following key casts will occur:
- Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
- Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under
8.
- [...]
That's not related with the fact that PHP arrays are sparse.
You can verify all this with var_dump().
来源:https://stackoverflow.com/questions/26119524/php-array-integer-index-vs-string-index