9

If I want to use a PHP non-associative array like a dictionary and add a big key, how much memory will PHP allocate?

$myArray = Array();
$myArray[6000] = "string linked to ID 6000";
$myArray[7891] = "another key-value pair";

Will PHP also allocate memory for the unused keys 0-5999 and 6001-7890?

2 Answers 2

16

No, PHP doesn't implement this like a C style array. Php arrays are associative containers, as the php article on arrays states.

An array in PHP is actually an ordered map. A map is a type that associates values to keys.

Since order is preserved, the array will likely be some kind of binary search tree. If you're unfamiliar with binary search trees I suggest picking up a good data structures book to learn more or check out this wikipedia article for a rundown. Your example above would yield a binary search tree with two nodes -- one for data at key 6000, the other for key 7891.

3
  • 13
    Note that if you pass this through json_encode(), that'll create the 0-5999 keys - json doesn't like PHP's sparse arrays.
    – Marc B
    Commented Mar 5, 2011 at 16:08
  • When I do $myArray[strtotime($date)] = ... this runs of of memory, which seems to suggest otherwise. Commented May 9, 2016 at 16:05
  • 1
    No, whupps. I was trying to index a string with a huge number. That WILL crash. Stupid dynamic typing. Commented May 9, 2016 at 17:56
2

It won't allocate memory for indexes 0-5999.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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