如何在数组PHP中获取特定值
我想从数组中获得特定的值如何在数组PHP中获取特定值,php,arrays,Php,Arrays,我想从数组中获得特定的值 $countries=array(“af”=>“阿富汗”、“ax”=>“阿兰群岛”、“阿尔卑斯群岛”=>“阿尔巴尼亚”);“ 我在变量中有值 $country\u code=“ax” 使用这个变量,我想从数组中获取数组值 我是php新手,谢谢你你可以通过这种方式获得它 $value = $countries[$country_code]; $value=$countries[$country_code] 根据php文档: 可以使用Array[key]语法访问数组元素 在
$countries=array(“af”=>“阿富汗”、“ax”=>“阿兰群岛”、“阿尔卑斯群岛”=>“阿尔巴尼亚”);“
我在变量中有值
$country\u code=“ax”代码>
使用这个变量,我想从数组中获取数组值
我是php新手,谢谢你你可以通过这种方式获得它
$value = $countries[$country_code];
$value=$countries[$country_code] 根据php文档:
可以使用Array[key]语法访问数组元素
在您的代码中,它看起来像:$value=$countries[$country\u code]代码>
另外,我建议您在此处阅读PHP中的数组:
您的案例将在第6个示例中解释 只需在@B.Mossavari answer上展开,您应该在提取值之前检查键是否存在,否则PHP将返回未定义的索引通知
if (array_key_exists($country_code, $countries)) {
$value = $countries[$country_code];
} else {
$value = ''; // set value to something so your code doesn't fail later
}
这是我的首选方法,但您也可以使用isset($countries[$country\u code])
或进行检查!空($countries[$country\u code])
对于php7,您可以使用$countries[$country\u code]$国家[$国家/地区代码]:''