In PHP, there are many ways to achieve it Array key value exchange:
array_flip()
Function: is specially designed for array key value exchange with excellent performance.
$new_array = array_flip($old_array);
Self-written loop: Exchange keys and values by manually traversing the array.
$new_array = []; foreach ($old_array as $key => $value) { $new_array[$value] = $key; }
Use the array_combine()
and array_values()
functions: Separate keys and values into separate arrays , and then use array_combine()
to recombine.
$keys = array_keys($old_array); $values = array_values($old_array); $new_array = array_combine($values, $keys);
Algorithm selection has a significant impact on performance:
array_flip()
The performance is best for large arrays, while self-written loops are more efficient for small arrays. array_combine ()
is more suitable. Case 1: Small array
$old_array = ['foo' => 1, 'bar' => 2]; // 使用自写循环高效互换键值 $new_array = []; foreach ($old_array as $key => $value) { $new_array[$value] = $key; }
Case 2: Large array
$old_array = ['John' => 'Doe', 'Jane' => 'Smith']; // 使用 array_flip() 获得最佳性能 $new_array = array_flip($old_array);
Case 3: Key values are relevant
$old_array = [1 => 'foo', 2 => 'bar', 3 => 'baz']; // 使用 array_combine() 和 array_values() 保留键值相关性 $keys = array_keys($old_array); $values = array_values($old_array); $new_array = array_combine($values, $keys);
The above is the detailed content of PHP array key-value interchange: algorithm selection guide and performance factors. For more information, please follow other related articles on the PHP Chinese website!