[KLUG Programming] PHP arrays vs. structures

bill bill at billtron.com
Sat Jul 17 15:58:09 EDT 2004


On Sat, 2004-07-17 at 14:53, Adam Tauno Williams wrote:
> > I think all arrays are associative in PHP. 
> 
> That bites.  not so mon frere
> 
> > Your example isn't quite correct, but your question is valid.
> > To illustrate:
> > $colors = array('red', 'blue', 'green', 'yellow');
> > while (list($key,$val)=each($colors)) {
> > 	echo "key is $key: val is $val<br />\n";
> > } // end while
> > That above will show the same results as:
> > > $colors = array([0] => 'red',
> > >                 [1] => 'blue',
> > >                 [2] => 'green',
> > >                 [3] => 'yellow');
> 
> Ah, so all the arrays created in a non-associative (key'd) way get
> implicit numeric keys.  

Yup.

> This solves my problems 

A common PHP phrase

> since the structures I have to deal with never
> use numeric keys, so if the first key is 0 then it is an array,
> otherwise it must be a structure (keys are strings).  So I'm just lucky
> (for once!) in this case.

It's implicit, which means that unless the keys are explicitly set as
strings, you can refer to them numerically.  That tidbit can be
extremely helpful (because so much code doesn't explicitly set the
key).  In your case the check code you were looking for is not even
necessary.

Two other helpful tips: 

1) return values from a db call sets both (i.e., it is an associative
array of field names, as well as numerically indexed).  Use whatever you
want.  

2) Many times arrays have elements missing (think of online forms
submitting checkbox values).  So, use 

while (list($key,$val)=each($myarray)) {
	// do something with each element
} // end while

Instead of 

for ($i=0; $i<count($myarray); $i++) {
	// do something with each element
} // end for

The first will only iterate through actual elements, the second will hit
upon non-existent elements, which is often a problem.  

Don't forget to reset the array when done (you may want to go through it
again later).

kind regards,

bill



More information about the Programming mailing list