matt
matt

Reputation: 44303

php: get array value without iterating through it?

hey guys, i think i lost my mind.

print_r($location); lists some geodata.

array (
  'geoplugin_city' => 'My City',
  'geoplugin_region' => 'My Region',
  'geoplugin_areaCode' => '0',
  'geoplugin_dmaCode' => '0',
  'geoplugin_countryCode' => 'XY',
  'geopl ...

when I iterate through it with a foreach loop I can print each line. However shouldn't it be possible to just get a specific value out of the array?

like print $location[g4]; should print the countryCode shouldn't it? Thank you!

Upvotes: 1

Views: 1531

Answers (5)

SubniC
SubniC

Reputation: 10317

there you are using an associative array, it is an array with a user defined key:value pair (similar to dictionaries on Python and Hash Tables on C#)

You can access the elements just using the Key (in this case geoplugin_city or geoplugin_region)

Using the standard array syntax:

$arrayValue = $array[key];     //read
$array[key] = $newArrayValue;  //write 

For example:

$location['geoplugin_city']; or $location['geoplugin_region'];

If you are not familiarwith PHP arrays you can take a look here:

http://php.net/manual/en/language.types.array.php

For a better understanding on array manipulation with PHP take a look of:

http://www.php.net/manual/en/ref.array.php

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

Where does "g4" come from? Did you mean "4"?

If you had a normal numerically-indexed array then, yes, you could write $location[4]. However, you have an associative array, so write $location['geoplugin_countryCode'].

Upvotes: 0

bensiu
bensiu

Reputation: 25564

$location['geoplugin_countryCode'];

would access country code

Upvotes: 0

alexn
alexn

Reputation: 58962

Yes, you can get a specific value by key. The keys in your case are the geoplugin_ strings.

To get the country code:

// XY
$location['geoplugin_countryCode'];

Upvotes: 0

Andre Backlund
Andre Backlund

Reputation: 6943

echo $location['geoplugin_countryCode'];

Upvotes: 5

Related Questions