I’ve got this array (shortened for this question), and I need to extract the country_code (“AF” and “AL” in this demo) in order to insert the region info into a table based on the country.
How do I get the country code while iterating the array and is this the correct way to do this?
$countries = array("AF" => array("BDS" => "Badakhshan",
"BDG" => "Badghis",
"BGL" => "Baghlan",
"BAL" => "Balkh",
"BAM" => "Bamian",
"DAY" => "Daykondi"),
"AL" => array("BR" => "Berat",
"BU" => "Bulqizë",
"DL" => "Delvinë",
"DV" => "Devoll",
"DI" => "Dibër",
"DR" => "Durrës",
"EL" => "Elbasan",
"FR" => "Fier")
);
foreach ($countries as $country) {
$country_code = $country[]; // How do I get the country code here?
foreach ($country as $region_code => $region_name) {
// insert region info into table
} // foreach ($country as $region_code => $region_name)
} // foreach ($countries as $country)
Your array is setup with
key => valuepairs, meaning you have a value, and an identifier for that value.Or, in the case of your code:
If you wish to get the key while looping, use the following syntax:
Now you’re able to access the identifer with each iteration.