[KLUG Programming] PHP arrays vs. structures

bill bill at billtron.com
Sat Jul 17 11:51:31 EDT 2004


Hi Adam,

I think all arrays are associative in PHP.  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');

while (list($key,$val)=each($colors)) {
	echo "key is $key: val is $val<br />\n";
} // end while

A real associative array would look a bit different

$options=array(color=>'red', size=>'medium', qty=>3, pattern=>'plaid');

while (list($key,$val)=each($options)) {
	echo "key is $key: val is $val<br />\n";
} // end while

// this is the only one that will not show a numerical index.

This will show no values indexed numerically:

for ($i=0;$i<count($options)$i++) {
	echo "key is $i: val is $options[$i];
}

But, you can still show them like this:

print_r(array_values($options));

And this is cool, too:

print_r(array_keys($options));

I've never had to do specifically what you're after.  But you could
check the type of the key(s).  There are several functions to do that
you can see here (see the notes at the bottom):

http://php.net/is_array


kind regards,

bill

On Sat, 2004-07-17 at 10:59, Adam Tauno Williams wrote:
> In PHP one can have both unassociated arrays (true arrays) and
> associated arrays (really more like structures).
> 
> An unassociated array -
> $colors = array('red', 'blue', 'green', 'yellow')
> 
> And associated array =
> $colors = array([0] => 'red',
>                 [1] => 'blue',
>                 [2] => 'green',
>                 [3] => 'yellow');
> 
> If given the variable '$ralph' you can determine that it is an array via
> the use of gettype($ralph).  But what is the simplest method of
> determining if the array is an array or a structure, since PHP itself
> doesn't distinguish between these as two different types.
> 
> _______________________________________________
> Programming mailing list
> Programming at kalamazoolinux.org
> http://www.kalamazoolinux.org/mailman/listinfo/programming
> 



More information about the Programming mailing list