Home >Backend Development >PHP Problem >PHP changes the key values in the array to uppercase
In php, sometimes we need to change the key values in the array to uppercase. This requirement may appear when, for example, reading a database table, the field names obtained are lowercase, but we want to use uppercase to represent them.
So, how to change the key values in the array to uppercase? Two methods are introduced below.
Method 1: Use the array_change_key_case function
php provides the array_change_key_case function, which can convert all the key names of the array to uppercase or lowercase. We can use this function to change the key values in the array to uppercase. The sample code is as follows:
// 原始数组 $originalArray = array("name"=>"Tom", "age"=>20, "gender"=>"male"); // 使用array_change_key_case函数将键名全部转为大写 $newArray = array_change_key_case($originalArray, CASE_UPPER); // 输出新的数组 print_r($newArray);
The output result is as follows:
Array ( [NAME] => Tom [AGE] => 20 [GENDER] => male )
As you can see, all the key values in the original array have been Convert to uppercase.
It should be noted that the array_change_key_case function does not modify the original array, but returns a new array. Therefore, it needs to be modified according to the actual situation in actual use.
Method 2: Use the array_map function
In addition to the array_change_key_case function, we can also use the array_map function to achieve the effect of changing the key values in the array to uppercase. The array_map function can apply a function to each element of the array. The sample code is as follows:
// 原始数组 $originalArray = array("name"=>"Tom", "age"=>20, "gender"=>"male"); // 定义一个函数,将字符串转为大写 function strToUpperCase($str) { return strtoupper($str); } // 使用array_map函数将原始数组的键名全部转为大写 $newArray = array_combine(array_map("strToUpperCase", array_keys($originalArray)), $originalArray); // 输出新的数组 print_r($newArray);
The output result is as follows:
Array ( [NAME] => Tom [AGE] => 20 [GENDER] => male )
As you can see, all the key values in the original array have been converted to capital.
It should be noted that the array_map function does not modify the original array, but returns a new array. At the same time, in order to ensure that the key names of the new array correspond to the key names of the original array, we use the array_combine function to splice the new key names and the values of the original array.
Summary:
Whether you use the array_change_key_case function or the array_map function, you can achieve the effect of changing the key values in the array to uppercase. Specific methods need to be selected as appropriate to meet actual development needs.
The above is the detailed content of PHP changes the key values in the array to uppercase. For more information, please follow other related articles on the PHP Chinese website!