Multi Dimensional Arrays

A

Anonymous

Guest
How can I handle multi dimensional arrays in PHP? Can it only be handled as a single dimension array using “loops” or there is a more practical way to store and retrieve related data using an array?

Thanks
 
Multi-dimensional arrays work fine in PHP, and pretty much like they do in any other language. A multi-dimensional array is just an array of arrays.

But the best approach really depends on what you're trying to accomplish.
 
Thanks.
I need to setup a 2D array for states and counties like the following:

NY Orange
NY Westchester
NY Rockland
NJ Bergen
NJ Milford
... .........
... .........
CA Ornage
... ..........

So I could recall all counties for NY or CA or... and be able to reference them with value like printing all counties of the NY.

Thanks again.
 
popeye said:
I need to setup a 2D array for states and counties like the following:

NY Orange
NY Westchester
NY Rockland
NJ Bergen
NJ Milford
... .........
... .........
CA Ornage
... ..........

I will warn you that if you're doing all 50 states, that's quite a lot of data to be putting in a single array. Anyway, here's the best way to do it in PHP:

<?php
$states_counties = array(
'NY' => array(
'Orange',
'Westchester',
'Rockland',
'Bergen',
'Milford',
/* ... */
),
'CA' => array(
'Orange',
/* ... */
);
?>

P.S. Sorry for the lack of indentation, but the code tags are a little messed up right now.
 
This looks great. I think I definitely can use it. I may include in it in some logic to read the data from a table in a database.
I will need some help in using two related "<select>" drop down menus in a page like when you pick the "state" from one menu the "county' menu shows only the counties of the selected state. But I think that is a JavaScript issue that I have to research.

Thanks again
 
Back
Top