There are three optimal solutions for key-value swapping in PHP: array_flip() function can quickly swap arrays of unique keys and values; array_combine() function merges two arrays to form a new array; custom functions can be used to customize repetitions Advanced requirements such as value processing. Choosing the best solution depends on key value uniqueness, number of duplicate values, and efficiency considerations.
PHP array key-value swapping: choosing the best solution
In PHP, there is a very high demand for array key-value swapping common. This article will explore several of the most effective methods and provide practical examples for detailed explanation.
Method 1: Use the array_flip() function
array_flip()
is a built-in function that can interchange the keys and values of the array. The syntax is as follows:
$new_array = array_flip($array);
Advantages:
Disadvantages:
Practical case:
Suppose we need to ['name' => 'John', 'age' => 30]
Swap the key values of the array.
$array = ['name' => 'John', 'age' => 30]; $new_array = array_flip($array); foreach ($new_array as $key => $value) { // 遍历新数组 echo "$key: $value<br>"; }
Output:
John: name 30: age
Method 2: Use array_combine() function
array_combine()
The function can use two Array generates a new array with one array as keys and another array as values. The syntax is as follows:
$new_array = array_combine($keys, $values);
Advantages:
Disadvantages:
Practical case:
Suppose we need to change the key to ['John', 'Mary']
and the value to ## The two arrays of #[30, 25] are combined into a new array.
$keys = ['John', 'Mary']; $values = [30, 25]; $new_array = array_combine($keys, $values); foreach ($new_array as $key => $value) { // 遍历新数组 echo "$key: $value<br>"; }
John: 30 Mary: 25
Method 3: Use custom function
We can also write our own function to realize the key-value swap function. The syntax is as follows:function flip_array($array) { $new_array = []; foreach ($array as $key => $value) { $new_array[$value] = $key; } return $new_array; }
Advantages:
Disadvantages:
Practical case:
We can use this custom function to reverse['name' => 'John', 'age' => 30] Key value of the array.
function flip_array($array) { // 使用自定义函数 $new_array = []; foreach ($array as $key => $value) { $new_array[$value] = $key; } return $new_array; } $array = ['name' => 'John', 'age' => 30]; $new_array = flip_array($array); foreach ($new_array as $key => $value) { // 遍历新数组 echo "$key: $value<br>"; }
John: name 30: age
Select the best solution
The choice of the best solution depends on the specific needs:.
.
and
array_combine() are generally faster.
The above is the detailed content of PHP array key value swap: choosing the best solution. For more information, please follow other related articles on the PHP Chinese website!