Andrej
Andrej

Reputation: 187

Return A Single Variable From Array

i am using following script:

http://www.micahcarrick.com/php-zip-code-range-and-distance-calculation.html

To get the details for a ZIP code, I am using this:

$selected = $z->get_zip_details($zip);
$result = implode(",", $selected);
echo $result;

This returns all details of "$zip" :

32.9116,-96.7323,Dallas,Dallas,TX,Texas,214,Central

Could any1 help me to make the script return ONLY the city variable? The FAQ of the script, says the following:

get_zip_details($zip)

Returns the details about the zip code: $zip. Details are in the form of a keyed array. The keys are: latitude, longitude, city, county, state_prefix, state_name, area_code, and time_zone. All are pretty self-explanitory. Returns false on error.

Unfortunately I cant figure out how to get a single value (city). Would appreciate any help!

Thanks!

Upvotes: 0

Views: 285

Answers (3)

Phoenix
Phoenix

Reputation: 4536

For future reference, implode() explode() etc. are array functions. So, if you're using them on something then you can print_r() it to see its structure.

If you had done print_r($selected); or var_dump($selected);, you would have gotten something like this as output:

Array ( [x] => 32.9116 [y] =>-96.7323 [city] => Dallas [state] => Texas [etc] => etc )

So you can see the keys of the array to know how to access the individual values.

Upvotes: 0

Michiel Pater
Michiel Pater

Reputation: 23033

Change this line

$result = implode(",", $selected);


To

$result = $selected['city'];

Upvotes: 1

Andre Backlund
Andre Backlund

Reputation: 6943

The functions is returning an array, so we have to store it in a variable.

    $selected = $z->get_zip_details($zip);

Next, we can select the key which points to the city. The key is also called city.

  echo $selected['city'];

Upvotes: 1

Related Questions