PHP – Are PHP Arrays Dynamic Data Structures?

arraydata structuresdynamic-dataPHP

I did my homework, and it says that dynamic data structures are "data structures that change in size as a program needs it to by allocating and de-allocating memory from the heap".

So I was wondering, are PHP arrays examples of dynamic data structures, or are they limited to binary trees and double-linked lists?

Thanks.

Best Answer

Yes, PHP arrays are dynamic, in the sense that one can create an array, insert new elements, delete elements, etc. without ever worrying about its size. The array grows or shrinks as needed, automatically.

You didn't quite fully "do your homework" though, since most PHP programming books would have told you the above :) By the way, if you need a recommendation, I'd go for O'Reilly's "Programming PHP".

One particularity about PHP arrays is that they are all implemented as associative arrays i.e., ordered collections of key-value pairs (a.k.a. maps, or hash tables). Even a "plain" array of, say, strings, is an associative array where the keys are (automatically generated) indices. For instance, array("a", "b", "c") is actually the same as array(0 => "a", 1 => "b", 2 => "c"). It's a very interesting design...

The last part of your question is rather puzzling, though, i.e. "are PHP arrays examples of dynamic data structures, or are they limited to binary trees and double-linked lists?" Because, binary trees and linked lists are typical examples of dynamic structures as well! (where a node is inserted or removed every time an item is added or deleted from the data structure) So it's like asking if an apple is red or red...

This Wikipedia page compares programming languages and, in particular, tells you which languages support dynamic arrays, or not:
http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(array)