我想從數組中獲得特定值。如何獲得數組中的特定值PHP
$countries = array("af"=>"Afghanistan","ax"=>"Aland Islands","al"=>"Albania);"
,我有可變
$country_code="ax";
值使用這個變量我想從陣列陣列值
我是新來的PHP,謝謝
我想從數組中獲得特定值。如何獲得數組中的特定值PHP
$countries = array("af"=>"Afghanistan","ax"=>"Aland Islands","al"=>"Albania);"
,我有可變
$country_code="ax";
值使用這個變量我想從陣列陣列值
我是新來的PHP,謝謝
你可以這樣得到
$value = $countries[$country_code];
根據PHP文檔:
數組元素可以使用陣列[鍵]語法來訪問。
在你的代碼,它會看起來像:$value = $countries[$country_code];
此外,我建議你閱讀有關的PHP這裏數組: http://php.net/manual/en/language.types.array.php 你的情況是在第6爲例進行說明。
只是爲了擴大對@ B.Mossavari答案,你應該檢查,關鍵是有提取值或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_code])
或!empty($countries[$country_code])
或!empty($countries[$country_code])
更好的方法是這樣的:$ value =(array_key_exists($ country_code,$ countries))? $國家[$ country_code]:''' –
對於php7,您可以使用'$ countries [$ country_code] ?? null',如果數組中沒有一個,則返回null。 –