Reputation: 6057
I'm developing a PHP library and I'd like to add some hard coded data using arrays. How do I determine the optimal way to structure the data in terms of the array keys and values? For example, if I wanted to do the United States I could go:
$states = array( 'AL' => 'Alabama', 'AZ' => 'Arizona', ...);
Or instead I could go:
$states = array( array('AL', 'Alabama'), array('AZ', 'Arizona'), ...);
I feel like the second option might be better because then I could consistently structure all data that way regardless of how many "fields" there are because it is more akin to database rows.
Edit: To clarify, I'm looking fot a generic solution or set of rules I can use. For example the data may be something other than the United States and have 1 field or 8 fields instead of 2. In these cases there may not be something I can use for the key. Another question is do I want all the data arrays to have the same structure or should I use whatever best fits the specific data set?
Upvotes: 2
Views: 3775
Reputation: 4946
The first one is better. You can use the foreach command in php
foreach($states as $key => $value){
echo $key . " = " . $value . "<br/>";
}
So you can manipulate with your $key and $value
instead of: echo $key . " = " . $value . "<br/>";
do
foreach($states as $key => $value){
echo $states[$key] . "<br/>";
// or simply echo $value of course
}
That will only give you the full names, but based on the $key.
Bottom line is that the first one is stronger in this particular application of array().
Upvotes: 1
Reputation: 6426
I would pick the first one.
$states = array(
'AL' => 'Alabama',
'AZ' => 'Arizona',
...);
and if you required more fields you can always use the nested solution:
$states = array(
'AL' => array( name => 'Alabama', population => 104 ),
'AZ' => array( name=> 'Arizona', population => 121 ),
...);
or
$states = array(
'AL' => array( 'Alabama', 104 ),
'AZ' => array( 'Arizona', 121 ),
...);
Upvotes: 1
Reputation: 30488
this creates key=>value pair
$states = array(
'AL' => 'Alabama',
'AZ' => 'Arizona',
...);
this creates all values with default keys
$states = array(
array('AL', 'Alabama'),
array('AZ', 'Arizona'),
...);
The first approach of using key=>value
pair is best for your need.
Upvotes: 2
Reputation: 157334
I would go for the first approach, because it is not nested, secondly it will be easy to loop through without having nested loops, also in this case you do not require nested array.
Upvotes: 1