4

i have created an array like

arr[15] = "hello";
arr[21] = "world";

there are empty indexes from 0 to 14 and 15 to 20 . does these empty indexes are stored in memory or not . do they cause memory consumption . is it ok to have random indexes for array thanks

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
tauqeer
  • 41
  • 3
  • 1
    From where the empty indexes are created? – Sougata Bose Jun 23 '15 at 09:34
  • 4
    Unless you specify `$arr[14]=0;` they don't exist, so don't consume memory. The "index" is merely an pointer to a location - it doesn't mean that every location preceding it has to exist :) – Fluffeh Jun 23 '15 at 09:37
  • very easy to chek with if(isset(arr[10])) .. blabla – Grumpy Jun 23 '15 at 09:37
  • 1
    Check [this answer](http://stackoverflow.com/a/25114841/2637490) - despite different context, it explains array structure (prior to PHP 7) quite well – Alma Do Jun 23 '15 at 10:14

2 Answers2

1

PHP arrays are associative, also known as dictionaries, also known as hashmaps, also known as key-value store. There's no relationship between keys, meaning the existence of a key 15 does not imply the existence of a key 14, just as the existence of a key 'foo' does not imply the existence of a key 'bar'. PHP arrays are therefore all sparse. When you create the key 15 PHP does not populate keys 0-14. They do not exist and do not occupy memory.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

here are empty indexes from 0 to 14 and 15 to 20 . does these empty indexes are stored in memory or not . do they cause memory consumption

If you have created an array which consists these keys,then Yes they will occupy memory

If you're creating an array as

$array = array();
var_dump(isset($array));//bool(true)

Then its also consume memory too. So if your array consist the empty value then it'll be consuming memory too

Null will be cast to the empty string, i.e. the key null will actually be stored under "".

Check Docs

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54