In PHP, array keys and values can be exchanged through the following methods: array_flip() function: simple syntax, direct key-value exchange, time complexity O(n). Custom function: flexible and can be customized according to needs, but the time complexity is also O(n). Shift operators: Requires PHP knowledge, more efficient in some cases, still O(n) time complexity.
In PHP, it is often necessary to exchange the array key and value so that for further processing. There are multiple ways to do this, each with its pros and cons.
array_flip()
The function is a built-in function provided by PHP that is directly used to exchange array values and keys. Using it is very simple, just pass the original array as a parameter:
$originalArray = [ 'name' => 'John Doe', 'age' => 30, ]; $flippedArray = array_flip($originalArray); print_r($flippedArray);
Output:
Array ( [John Doe] => name [30] => age )
You can also define a custom one function to interchange array values and keys:
function flipArray($array) { $flippedArray = []; foreach ($array as $key => $value) { $flippedArray[$value] = $key; } return $flippedArray; }
This custom function works similarly to the array_flip()
function, but it provides greater flexibility. For example, you can add additional logic to handle special cases or modify the output format as needed.
The displacement operator (=>
) can also be used to interchange array keys and values. This approach requires a certain level of PHP knowledge, but it may be more efficient than others in some cases:
$originalArray = [ 'name' => 'John Doe', 'age' => 30, ]; $flippedArray = []; foreach ($originalArray as $key => $value) { $flippedArray[$value] = $key; }
Practical Case
Suppose there is a An array of product information, whose price needs to be obtained based on the product name. Arrays can be quickly transformed using value and key swapping to easily find the price data you need:
$products = [ 'Apple' => 10, 'Orange' => 5, ]; // 使用 array_flip() 互换键和值 $flippedProducts = array_flip($products); // 根据产品名称获取价格 $price = $flippedProducts['Orange'];
In the above example, $price
will now contain the product Orange
price without traversing the entire original array to find it.
Here is a quick comparison of performance when using different methods to swap arrays:
Method | Time complexity |
---|---|
##array_flip()
| O(n)|
O(n) | |
O(n) |
The above is the detailed content of PHP array value and key interchange: implementation and performance comparison. For more information, please follow other related articles on the PHP Chinese website!