← Back to all snippets
PHP

Swap Keys and Values in a PHP Array

Learn how to easily invert a PHP associative array, turning its keys into values and its values into keys, using the `array_flip()` function for quick data transformation.

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

echo "Original array:
";
print_r($countryCodes);

$countries = array_flip($countryCodes);

echo "
Flipped array (keys become values, values become keys):
";
print_r($countries);

// Example with duplicate values - only the last one is kept
$colors = [
    'red_hex' => '#FF0000',
    'green_hex' => '#00FF00',
    'blue_hex' => '#0000FF',
    'crimson_hex' => '#FF0000' // Duplicate value
];

echo "
Original array with duplicate values:
";
print_r($colors);

$flippedColors = array_flip($colors);

echo "
Flipped array with duplicate values (last one wins):
";
print_r($flippedColors);
?>
How it works: The `array_flip()` function exchanges all keys with their associated values in an array. This is extremely useful when you need to quickly reverse the lookup direction for an associative array. It's important to note that if multiple values are identical, only the key associated with the *last* occurrence of that value will be used as the new value, overwriting previous ones.

Need help integrating this into your project?

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

Hire DigitalCodeLabs