Jump to content

How do I turn a variable into an array?


horseatingweeds

Recommended Posts

I'm having trouble understanding this of finding an example.

 

How do I make a variable like this:

 

$state = "\

US:AK:Alaska|\

US:AL:Alabama|\

US:AR:Arkansas|\

US:AS:American Samoa|\

US:AZ:Arizona|\

";

 

Into an array? I then want to cut each array value into its three parts so I can convert the state code to the actual name.

Link to comment
https://forums.phpfreaks.com/topic/62590-how-do-i-turn-a-variable-into-an-array/
Share on other sites

If you want state code => name, try this:

 

$state_arr = explode("|\n", $state); # if "|\n" is the delimineter
$lookup_tab = array();
foreach ($state_arr as $s) {
  list($country, $code, $name) = explode(':', $s);
  $lookup_tab[$code] = $name;
}
print_r($lookup_tab);

Not 100% sure what you want here.. but maybe something like this:

 

$state_arr = explode("|\n", $state); # if "|\n" is the delimineter
$lookup_tab = array();
$i = 0;
foreach ($state_arr as $s) {
  list($country, $code, $name) = explode(':', $s);
  print "$i, $country, $code, $name\n";
  $lookup_tab[$code] = $name;
  $i++;
}
print_r($lookup_tab);

 

I haven't actually stored the numerical index because I'm not sure where you want it.  But that code should demonstrate how to make it available.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.