# Array index question

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
I have source information in a file, and (part of) this information comes as
coordinates.
A coordinate consists of a letter followed by a number, ranging from a1 to
i9
I'd like to count the number of occurrences of each coordinate, and put them
in a matrix.
The matrix should look like this (metasyntax):

matrix = array ['a'..'i'][1..9]

Later on in the script I'd like to be able to refer to a cell in the matrix
by using the same letter/number combo.
I know I can define an array using strings as keys, but how can I define
a..i as keys without the need to specify them all individually?
TIA
Pjotr

## Re: Array index question

"Pjotr Wedersteers" wrote:
> I have source information in a file, and (part of) this information
> comes as
> coordinates.
> A coordinate consists of a letter followed by a number, ranging
from
> a1 to
> i9
> I’d like to count the number of occurrences of each coordinate,
> and put them
> in a matrix.
> The matrix should look like this (metasyntax):
>
> matrix = array [’a’..’i’][1..9]
>
> Later on in the script I’d like to be able to refer to a cell in
> the matrix
> by using the same letter/number combo.
> I know I can define an array using strings as keys, but how can I
> define
> a..i as keys without the need to specify them all individually?
> TIA
> Pjotr

Hope this helps.

Read the coordinates from the file. I assume after you read then, they
are going to be in an array  called \$coor, where \$coord would have
values like ’a1’ , ’b5’, etc.

Then do this:
foreach (\$coord as \$line) {
\$alpha = preg_replace("/\d/", ’’, \$line);  //leaves only the
alpha part
\$num = preg_replace("/\D/", ’’, \$line);  //leaves the numeric
part only
\$newcoord[\$alpha][\$num] += 1; //increment count

}

You now have the counts for each coordinate combination.

--
Articles individually checked for conformance to usenet standards
Topic URL: http://www.dbForumz.com/PHP-Array-index-ftopict131894.html
Visit Topic URL to contact author (reg. req'd).  Report abuse:
http://www.dbForumz.com/eform.php?p=440194

## Re: Array index question

steve wrote:

Now that's a neat solution. Elegant too! Thanks a lot! Good thinking.
Pjotr

## Re: Array index question

.oO(Pjotr Wedersteers)

For example in a loop. This creates the empty matrix:

\$matrix = array();
for (\$i = ord('a'); \$i <= ord('i'); \$i++) {
\$matrix[chr(\$i)] = array_fill(1, 9, 0);
}

or

\$matrix = array();
foreach (range('a', 'i') as \$i) {
\$matrix[\$i] = array_fill(1, 9, 0);
}

Then you can access the elements like this:

\$coord = 'i9';
\$matrix[\$coord][\$coord]++;

HTH
Micha

## Re: Array index question

Michael Fesser wrote:

Okay, thanks Micha. This will work. The range solution seems best suited for
me here. !
Pjotr