Does PHP have built-in data structures?

Mar 12, 2012   //   by phpfreelancer.biz   //   Blog, PHP Tutorial  //  No Comments

The associative array can be used for most basic data structures hashtable, queue, stack. But if you want something like a tree or heap I don’t think they exist by default but I’m sure there are free libraries anywhere.

To have an array emulate a stack use array_push() to add and array_pop() to take off

To have an array emulate a queue use array_push() to enqueue and array_shift() to dequeue

An associative array is a hash by default. In PHP they are allowed to have strings as indexes so this works as expected:

$array[‘key’] = ‘value’;

Finally, you can kind of emulate a binary tree with an array with the potential to have wasted space. Its useful if you know you’re going to have a small tree. Using a linear array, you say for any index (i) you put its left child at index (2i+1) and right child at index (2i+2).

All of these methods are covered nicely in this article on how to make JavaScript arrays emulate higher level data structures.

Leave a comment

Share This Post

RSS Wordpress News