PHP
Invert Keys and Values of an Array
Quickly swap keys with their corresponding values in a PHP array using the `array_flip()` function, perfect for creating efficient lookup tables from existing data.
<?php
$countryCodes = [
'USA' => 'US',
'Canada' => 'CA',
'Mexico' => 'MX',
'Germany' => 'DE'
];
// Invert the array: codes become keys, countries become values
$codeToCountry = array_flip($countryCodes);
print_r($codeToCountry);
echo "
";
$colors = ['red', 'green', 'blue'];
// Numeric keys become values, and values become numeric keys
$flippedColors = array_flip($colors);
print_r($flippedColors);
?>
How it works: The `array_flip()` function is used here to exchange all keys with their associated values in an array. This is particularly useful when you have an array where the values are unique and you need to quickly look up the original keys based on those values. If a value appears more than once in the original array, the last key associated with that value will be used as its value in the flipped array.