Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory usage of a PHP array when adding a huge numeric key

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?

like image 360
philsch Avatar asked Mar 05 '11 14:03

philsch


People also ask

How many elements can a PHP array hold?

2,147,483,647 items, even on 64-bit PHP. At least, the largest array you can have with array_fill() or range() appears to be 2^32-1 items. While keys can be anything, including numbers outside that range, if you start at zero, with a step size of 1, your highest index can be 2147483646.

What is the main benefit of the array keyword in PHP?

Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data.

What is numeric array in PHP?

Numeric arrays allow us to store multiple values of the same data type in a single variable without having to create separate variables for each value. These values can then be accessed using an index which in case of numeric arrays is always a number. Note: By default the index always starts at zero.

How to declare a PHP array?

To create an array, you use the array() construct: $myArray = array( values ); To create an indexed array, just list the array values inside the parentheses, separated by commas.


2 Answers

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.

like image 143
Doug T. Avatar answered Oct 12 '22 11:10

Doug T.


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

like image 2
David Gillen Avatar answered Oct 12 '22 10:10

David Gillen