Does PHP have built-in data structures?

Viewed 60319

I'm looking at the PHP Manual, and I'm not seeing a section on data structures that most languages have, such as lists and sets. Am I just blind or does PHP not have anything like this built in?

10 Answers

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.

PHP has arrays, which are actually associative arrays and can also be used as sets. Like many interpreted languages, PHP offers all this under one hood instead of providing different explicit data types.

E.g.

$lst = array(1, 2, 3);
$hsh = array(1 => "This", 2 => "is a", 3 => "test");

Also, take a look in the manual.

PHP's array doubles as both a list and a dictionary.

$myArray = array("Apples", "Oranges", "Pears");
$myScalar = $myArray[0] // == "Apples"

Or to use it as an associative array:

$myArray = array("a"=>"Apples", "b"=>"Oranges", "c"=>"Pears");
$myScalar = $myArray["a"] // == "Apples"

I think you might want to be a bit more specific, when you say data structures my mind goes in a few directions...

Arrays - They are certainly well documented and available in. (http://us.php.net/manual/en/book.array.php)

SQL Data - Depends on the database you are using, but most are available. (http://us.php.net/manual/en/book.mysql.php)

OOP - Depending on the version objects can be designed and implemented. (http://us.php.net/manual/en/language.oop.php) I had to search for OOP to find this on the php site.

Of course PHP has data structures. The array in php is incredibly flexible. Some examples:

$foo = array(
  'bar' => array(1,'two',3),
  'baz' => explode(" ", "Some nice words")
);

Then you have an absolute plethora of array functions available to map/filter/walk/etc the structures, or convert, flip, reverse, etc.

Related