Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
    
It gives you an Undefined index 0/4 PHP warning. –  TiMESPLiNTER 43 mins ago
    
@TiMESPLiNTER Could you please clarify why it gives that error? I thought in PHP, there is no need for variable declaration. –  lonekingc4 42 mins ago
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 41 mins ago
    
@TiMESPLiNTER Okay, so is that memory unallocated? I mean, even if I use $arr[1000] directly, the first 999 indices are not wasted? –  lonekingc4 40 mins ago
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 25 mins ago

1 Answer 1

up vote 2 down vote accepted

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.