In PHP, the array_combine function is usually used to combine two arrays into an associative array, with elements of one array as keys and elements of the other array as values. However, if we want to invert the keys and values of an array, that is, we use the original value as keys and the original keys as values, array_combine is not directly used to implement. But we can easily implement this function by combining other PHP functions.
Suppose we have a simple array:
$array = [
'a' => 1,
'b' => 2,
'c' => 3
];
If we want to invert the key-value pairs in this array, we get the following result:
[
1 => 'a',
2 => 'b',
3 => 'c'
]
PHP provides a very convenient function array_flip() , which just implements the need for key-value pair inversion. It swaps the keys and values of the array, the original value becomes the new key, and the original key becomes the new value.
$array = [
'a' => 1,
'b' => 2,
'c' => 3
];
$flipped = array_flip($array);
print_r($flipped);
The output will be:
Array
(
[1] => a
[2] => b
[3] => c
)
Although array_flip() can perfectly solve the problem of key-value pair inversion, we can use array_combine() to achieve more customized inversion logic. For example, we can first get the value and key of the array, and then create a new array through array_combine .
Here is how to manually implement key-value pair inversion using array_combine() :
$array = [
'a' => 1,
'b' => 2,
'c' => 3
];
$keys = array_values($array); // Get the value part of the original array
$values = array_keys($array); // Get the key part of the original array
$reversed = array_combine($keys, $values); // Swap values with keys
print_r($reversed);
Output result:
Array
(
[1] => a
[2] => b
[3] => c
)
Value uniqueness : array_combine() requires that the value part and key part of the array must have the same length. If the two arrays have different lengths, array_combine() will throw an error. Therefore, when using array_combine() , you need to ensure that the size of the array is consistent.
Values can be used as keys : the inverted value will be used as the keys for the new array, and in PHP, the keys of the array are unique, so the value of the original array must be unique. If there are duplicate values, array_combine() will lose some of the data.
URL domain name replacement : When processing URLs, if you need to replace the domain name in the URL, you can use str_replace() to complete it. For example, if the domain name in the URL needs to be unified to m66.net , you can do this: