Wed 28 Jun 2006
PHP Array - jack of all trades
Posted by dkaz under Programming, PHP
One of the more intriguing features of PHP (from the perspective of someone exposed to it for the first time) is the amazing versatility of the Array class.
from php.net:
An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.
from Wikipedia:
Arrays are heterogeneous, meaning a single array can contain objects of more than one type. They can contain any type that PHP can handle, including resources, objects, and even other arrays. Order is preserved in lists of values and in hashes with both keys and values, and the two can be intermingled.
Since I’m scheduled to hack a bit of PHP in the next couple of months, I’m trying to figure whether I’ll be detesting seeing this kind of code:
$a=array(’fruits’=>array(’a'=>’orange’,'b’=>’grape’,c=>’apple’),
‘numbers’=>array(1,2,3,4,5,6),
‘holes’=>array(’first’,5=>’second’, ‘third’)
);

June 28th, 2006 at 5:38 am
You can also use another syntax:
$a[”fruits”] = array(”a”=>”orange”, “b”=>”grape”, c=>”apple”)
or
$a[”fruits”][”a”] = “orange”;
$a[”fruits”][”b”] = “grape”;
$a[”fruits”][”c”] = “apple”;
June 29th, 2006 at 12:18 am
I agree, PHP arrays are goofy. I’ve mucked around with them a lot in the past month. One useful trick for lazy people like me… uh, I mean, for prototyping… stick a result set from a database query in an array (instead of creating an object) and pass that from your data layer to your presentation layer.
Oh what I’d give for javadoc quality PHP documentation!
Good luck!