Home >Backend Development >PHP Problem >How to change the key value of php array
In PHP, array is a very commonly used data type. When writing code, we may need to modify the key values of the array. Several methods of modifying array key values will be introduced below.
Method 1: Use the unset() and array_values() functions
This is a relatively simple method. It first uses the unset() function to remove the original key value, and then uses array_values( ) function re-indexes the array and creates new key values.
The following is the sample code:
$old_array = array("key1" => "value1", "key2" => "value2", "key3" => "value3"); unset($old_array["key1"]); // 移除 "key1" 键 $new_array = array_values($old_array); // 重新索引数组并赋值给新数组 print_r($new_array); // 输出结果为:Array ( [0] => value2 [1] => value3 )
Method 2: Use array_combine() function
array_combine() function combines two arrays into a new array, the first array The key value in the second array is used as the key of the new array, and the key value in the second array is used as the value of the new array. Therefore, we can create a new array with a new key array and the original array's value array as parameters, so that we can change the array's key values.
The following is a sample code:
$old_array = array("key1" => "value1", "key2" => "value2", "key3" => "value3"); $new_keys = array("new_key1", "new_key2", "new_key3"); $new_array = array_combine($new_keys, array_values($old_array)); print_r($new_array); // 输出结果为:Array ( [new_key1] => value1 [new_key2] => value2 [new_key3] => value3 )
Method 3: Use array_map() function and anonymous function
array_map() function returns a new array whose value is the original array passed Specifies the value processed by the function. We can use an anonymous function as a parameter to modify the keys of the original array.
The following is a sample code:
$old_array = array("key1" => "value1", "key2" => "value2", "key3" => "value3"); $new_array = array_map(function($key) { return "new_" . $key; // 在原始键前添加 "new_" }, array_keys($old_array), $old_array); print_r($new_array); // 输出结果为:Array ( [new_key1] => value1 [new_key2] => value2 [new_key3] => value3 )
All three methods can modify the key value of the array. In actual applications, the appropriate method can be selected according to different situations.
The above is the detailed content of How to change the key value of php array. For more information, please follow other related articles on the PHP Chinese website!