2013-08-01 106 views
1

這裏是陣列數組大寫。需要檢查大寫和小寫

$country_codes_with_euro_currency = array('AT', 'BE', 'CY', 'DE', 'EE', 'GR', 'ES', 'FI', 'FR', 'IE', 'IT', 'LU', 'MT', 'NL', 'PT', 'SI', 'SK'); 

例如$result = 'at';

然後

if (in_array(trim($result), $country_codes_with_euro_currency)) { 
echo $currency_code = 'EUR'; 
} 

輸出就什麼都不是。需要$result = 'AT';

因此,要檢查大寫和小寫,但不希望手動重寫小寫數組。

創造了這樣的代碼

$country_codes_with_euro_currency = array_merge($country_codes_with_euro_currency, (array_map('strtolower', $country_codes_with_euro_currency))); 

有沒有更好的(短)的解決方案?

...關於標記爲重複只想通知我不問如何將大寫轉換爲小寫。在我的代碼中已經使用了strtolower。我展示我的方式如何得到結果。並要求爲更好的方法如何得到同樣的結果

最終解決

其實這種情況下,一個簡單的解決方案。

請假$country_codes_with_euro_currency原樣(大寫)。

而只是$result = strtoupper(trim($result));

然後if (in_array(trim($result), $country_codes_with_euro_currency))

請,在這裏Does PHP include toupper and tolower functions?就是這樣的答案(標記爲重複的)?我找不到......

回答

2

嘗試用strtoupperstrtolower

if (in_array(strtoupper(trim($result)), $country_codes_with_euro_currency)) { 
    echo $currency_code = 'EUR'; 
} 

如果你想檢查較低的情況下,那麼你可以把OR與條件

in_array(strtolower(trim($result)), $country_codes_with_euro_currency) 

所以應該就像

if (in_array(strtoupper(trim($result)), $country_codes_with_euro_currency) || 
    in_array(strtolower(trim($result)), $country_codes_with_euro_currency)) { 
     echo $currency_code = 'EUR'; 
} 

而作爲JimL說可以做更改上或下兩個結果和數組一樣

$converted_array = array_map("strtoupper", $country_codes_with_euro_currency); 
if (in_array(strtoupper(trim($result)),$converted_array)) 
{ 
    echo $currency_code = 'EUR'; 
} 
+0

我想看看兩者。看起來你的建議之前,編輯將是可以的。 if(in_array(strtoupper(trim($ result)),$ country_codes_with_euro_currency)|| in_array(strtolower(trim($ result)),$ country_codes_with_euro_currency)){echo $ currency_code ='EUR'; }'我會用它(假設沒有更短的代碼) – user2465936

+0

Yah現在我只是這樣說,但只是爲了讓你明白我只是將它們分開 – Gautam3164

+1

爲什麼不只是確保兩者都是大寫還是小寫呢?當你知道需求和乾草堆是一個或另一個時,你不必做兩個if /檢查。像這樣:'if(in_array(strtoupper(trim($ result)),strtoupper($ country_codes_with_euro_currency))){echo $ currency_code ='EUR'; }' – JimL