PHP array: integer index vs string index

夙愿已清 提交于 2019-12-23 13:44:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!