PHP

Flip Keys and Values in a PHP Array

Learn to quickly swap keys and values in a PHP associative array using `array_flip()`, creating a useful reverse lookup table for efficient data access.

<?php
$countryCodes = [
    'US' => 'United States',
    'CA' => 'Canada',
    'MX' => 'Mexico',
];

// Flip keys and values
$codeToCountry = array_flip($countryCodes);

print_r($codeToCountry);

// Example of using the flipped array for reverse lookup
echo "Country for US: " . ($countryCodes['US'] ?? 'N/A') . "
";
echo "Code for Canada: " . ($codeToCountry['Canada'] ?? 'N/A') . "
";

// Handle potential duplicate values (the last one wins)
$colors = ['red' => '#FF0000', 'green' => '#00FF00', 'blue' => '#0000FF', 'crimson' => '#FF0000'];
$flippedColors = array_flip($colors);
print_r($flippedColors); // crimson will overwrite red as key
?>
How it works: The `array_flip()` function is a simple yet powerful tool for reversing the roles of keys and values in an associative array. It's particularly useful for creating quick lookup tables where you need to find a key based on its value. Be aware that if multiple values are identical, the last one encountered will overwrite previous entries in the flipped array.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs