|
Posted by Lars Eighner on 11/02/05 13:12
In our last episode,
<43685993$0$93694$892e7fe2@authen.white.readfreenews.net>,
the lovely and talented MBS
broadcast on alt.php:
> Greetings. I'm still pretty new to PHP and I have a question. I know that
> variables are preceeded by a "$" (dollar sign). Typically, a variable has
> one value, unless it is an array. Then it is essentially a pointer to
> numerous values sequential in memory. The code I'm looking at now is using
> the same variable name, but assigning a different "index" to it, if you
> will.
> For example, I see the following:
> $settings['use_default_images']
> $settings['doctype']
> $settings['theme_url']
> And many more.
> What is this feature called in PHP?
Pretty much the same thing it is called in Perl or any number
of other language. It is a hash (or associative array, if you
like big words or you are looking them up in an index).
I'm pretty sure you are used to arrays with number indices:
$a[0], $bugbear[15], $pinky[$i] where $i is an integer.
Associative arrays are very similar, but use strings as
indices. You have offered some examples, and $settings[$str]
is another where $str is a string. The strings used as indices
are called "keys" and they are *associated* with "values."
Now you probably have noticed, integers have a natural order.
But strings don't. So you have to be very careful if you ever
think of trying to do something like sort an associate array or
try to form and idea of "first," "last," or "next" in relation
to an associative array. There is no general guarantee of order
in an associate array.
Naturally, it seldom makes any sense to try to do arithmetic
on hash keys. In other words, you may be used to the idea
that if $a[$n] is a value in an array $a[$n+1] is the "next"
value (if there is one). But if you $jimmy['age'], then
$jimmy['age' + 1] is most likely nonsense. You can do
string operations on keys, although you may or may not ever
find a situation in which it is useful to do so (i.e.
$jimmy['ag' . 'e'] = $jimmy['age']). In particular,
if first you do $jimmy['age'] = 24; and then
$jimmy['apt'] = 1191; $jimmy['age' + 1] in general is not
equal to $jimmy['apt'].
Associative arrays are very good for operations with things
like databases and other sets of related data. It is much
easier to deal with $jimmy['age'] than to try to remember
whether age is $jimmy[5] or $jimmy[6]. Generally you don't care
whether Jimmy's age or his apartment number comes first in the
record, you just want to be sure you don't get them confused.
--
Lars Eighner eighner@io.com http://www.larseighner.com/
I don't see posts from or threads started from googlegroups.
War on Terrorism: Treat Readers like Mushrooms
"DO NOT USE photos on Page 1A showing civilian casualties from the U.S. war
on Afghanistan." -Memo, _Panama City_ (FL) _News Herald_
Navigation:
[Reply to this message]
|