Thursday, June 29, 2006

One Array to rule them all

I've been coding in php of late. So some thoughts on that...

Most languages have a few Data Structures (ds). Java has the excellent Collections framework which contains quite a few types of ds as shown in the figure



What I found in php was the array();

It can be used like...

$pasta = array('spaghetti', 'penne', 'macaroni');

In this case the array can be compared to a List or an Array.


You can also add an element to the end of an existing array with the array_push() function or remove an element from the end by using the array_pop() function.

Using the array_shift() and the array_unshift() function removing or adding elements to the beginning of the array can be done.

So now the array can work both as a Queue and a Stack.


Additionally it is possible to declare an array like..

$menu = array('breakfast' => 'bacon and eggs', 'lunch' => 'roast beef', 'dinner' => 'lasagna');

Here 'breakfast' is a key and 'bacon and eggs' is the value. Usually keys are numbers from 0 onwards. In effect our innocent array is now a Map as well.


All this is extremely great for learners. A few thoughts ..

1. The array exposes an API for all these ds'es. How can I enforce an array to act only as a Queue? Is the leakage of the abstraction too much.

2. How do they optimize? In Java I know the costs when I create a LinkedList or an ArrayList. Or use a TreeMap or HashMap. How is it done in php?

3. Also are there Sets in php where one object cannot be added twice. Maybe I am missing some ds library in php ;)

No comments: