php - 数组是大写的。需要同时检查大写和小写

标签 php arrays

这是数组

$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?是这样的答案(标记为重复)吗?我找不到...

最佳答案

尝试使用 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'; 
}

关于php - 数组是大写的。需要同时检查大写和小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17986646/

相关文章:

java - 检查数组长度是否是完全平方数

php - PHP 中的 DOM 操作

PHP 不停止包含(中断)

php - 转义引号的函数无法正常工作

c - 修复用于解决搜索范围的代码

c++ - 对象数组 - std::array - 构造函数初始化问题

php - 在 PHP 中使用 jQuery 而不是 cURL 进行 REST API 调用

php - SQL SUM() 不同表不同列

php - 访问多维数组中的数据

c - 二维动态字符串数组 realloc 导致错误