PHP
Swap Keys and Values in a PHP Associative Array
Efficiently exchange the roles of keys and values in a PHP associative array using the built-in array_flip() function, creating a new reversed mapping for quick lookups.
<?php
$colorCodes = [
'red' => '#FF0000',
'green' => '#00FF00',
'blue' => '#0000FF'
];
$codeColors = array_flip($colorCodes);
print_r($codeColors);
// Output:
// Array
// (
// [#FF0000] => red
// [#00FF00] => green
// [#0000FF] => blue
// )
// Important Note: If there are duplicate values, the last value's key will be used.
$duplicateValueArray = [
'admin' => 1,
'editor' => 2,
'viewer' => 1 // 'admin' key will be overwritten by 'viewer'
];
$flippedDuplicate = array_flip($duplicateValueArray);
print_r($flippedDuplicate);
// Output:
// Array
// (
// [1] => viewer
// [2] => editor
// )
How it works: The `array_flip()` function in PHP exchanges all keys with their associated values in an array. It's a quick and convenient way to reverse key-value pairs, often useful for creating lookup tables where you need to search by a value to find its corresponding key. A key consideration is that if multiple values in the original array are identical, only the key corresponding to the *last* occurrence of that value will be used in the flipped array, as array keys must be unique.