php: get array value without iterating through it?

本秂侑毒 提交于 2021-02-11 07:03:32

问题


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!


回答1:


echo $location['geoplugin_countryCode'];



回答2:


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'];



回答3:


$location['geoplugin_countryCode'];

would access country code




回答4:


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'].




回答5:


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



来源:https://stackoverflow.com/questions/5301065/php-get-array-value-without-iterating-through-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!