5

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]?

CluelessNoob
  • 688
  • 1
  • 9
  • 20
  • It gives you an `Undefined index 0/4` PHP warning. – TiMESPLiNTER Sep 30 '14 at 11:20
  • @TiMESPLiNTER Could you please clarify why it gives that error? I thought in PHP, there is no need for variable declaration. – CluelessNoob Sep 30 '14 at 11:20
  • 1
    Well you don't have an entry in your array with key `0` or `4`. It's an undefined index in this array. So if you use `$intIndex[0]` you will run into an `Undefined index` PHP warning. – TiMESPLiNTER Sep 30 '14 at 11:21
  • @TiMESPLiNTER Okay, so is that memory unallocated? I mean, even if I use $arr[1000] directly, the first 999 indices are not wasted? – CluelessNoob Sep 30 '14 at 11:22
  • I mean first 1000 (0-999) indices. – CluelessNoob Sep 30 '14 at 11:28
  • 1
    Yes that memory is unallocated. Because those indeces don't exist. But you allocate it "automatically" as soon as you give the array index a value. So `$intIndex[0] = 'foo';` will allocate memory for this specific index. – TiMESPLiNTER Sep 30 '14 at 11:37

1 Answers1

6

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().

Álvaro González
  • 142,137
  • 41
  • 261
  • 360