Sometimes you need to reverse the relationship between array keys and values. For example, you might have a list of names and want to use those names as keys for quick lookups.
PHP provides the array_flip() function to exchange array keys with their corresponding values.
In this guide, you'll learn how it works, how it handles duplicate values, and when it's useful.
What Is array_flip() in PHP?
The array_flip() function swaps the keys and values of an array.
Its syntax is:
array_flip(array $array): array
The function accepts one array and returns a new array in which:
- Original keys become values.
- Original values become keys.
The original array remains unchanged.
Important: The values in the original array must be strings or integers because they will become array keys.
Example 1: Flipping an Indexed Array
Let's start with a simple list of programming languages.
<?php
$languages = [
"PHP",
"Python",
"JavaScript"
];
$result = array_flip($languages);
print_r($result);
Output:
Array
(
[PHP] => 0
[Python] => 1
[JavaScript] => 2
)
Each language becomes an array key, and its original numeric index becomes the corresponding value.
You can now retrieve a language's original position directly:
echo $result["Python"];
Output:
1
Example 2: Flipping an Associative Array
The function also works with associative arrays.
<?php
$statusCodes = [
"success" => 200,
"not_found" => 404,
"server_error" => 500
];
$statuses = array_flip($statusCodes);
print_r($statuses);
Output:
Array
(
[200] => success
[404] => not_found
[500] => server_error
)
The numeric status codes become keys, making it easy to retrieve a status name using its code.
For example, $statuses[404] returns "not_found".
What Happens with Duplicate Values?
If the original array contains duplicate values, those values become duplicate keys after flipping.
Because PHP arrays cannot contain duplicate keys, the last matching entry wins.
<?php
$categories = [
"article1" => "PHP",
"article2" => "Python",
"article3" => "PHP"
];
print_r(array_flip($categories));
Output:
Array
(
[PHP] => article3
[Python] => article2
)
The PHP key contains article3 because its occurrence came later.
The reference to article1 is lost from the flipped result.
Therefore, array_flip() is not suitable when you need to preserve multiple original keys associated with the same value.
Practical Example: Finding Column Positions
Imagine you're processing a spreadsheet or CSV file. Its column order might change, but the column names remain consistent.
Instead of relying on fixed numeric positions, you can use array_flip() to create a lookup of column names and their indexes.
Create a file named column-lookup.php:
<?php
declare(strict_types=1);
// Column names from an imported table.
$headers = [
"sku",
"stock",
"name"
];
// One row of product data.
$row = [
"KB-101",
12,
"Keyboard"
];
// Create a column-name lookup.
$columns = array_flip($headers);
// Check that the required columns exist.
if (
!array_key_exists("name", $columns) ||
!array_key_exists("stock", $columns)
) {
exit("Required columns are missing.");
}
// Retrieve values by column name.
$productName = $row[$columns["name"]];
$stock = $row[$columns["stock"]];
// Display the result.
$message = $productName
. " - "
. $stock
. " in stock";
echo htmlspecialchars(
$message,
ENT_QUOTES,
"UTF-8"
);
Browser output:
Keyboard - 12 in stock
The flipped header array contains these mappings:
sku => 0
stock => 1
name => 2
If the columns appear in a different order, the lookup adjusts automatically.
This technique is useful when processing imported records, provided the header names are unique. For real external files, also validate row lengths and field values before accessing or using them.
Unsupported Values and Other Limitations
Only string and integer values can become keys in the flipped array.
If a value is an array, object, boolean, float, or null, PHP emits a warning and skips that entry.
Other important details:
- String keys are case-sensitive:
"PHP"and"php"remain different keys. - Numeric strings: Values such as
"123"may become integer keys. - Empty arrays: Flipping an empty array returns an empty array.
- Nested arrays: Arrays cannot be used directly as flipped keys.
Flipping an array twice does not always restore the original data. Duplicate values or key conversions may have already caused information to be lost.
array_flip() vs Related Functions
| Function | Purpose |
|---|---|
array_flip() |
Exchanges array keys and values. |
array_reverse() |
Reverses the order of array elements. |
array_keys() |
Returns the keys of an array. |
array_values() |
Returns the values of an array with sequential numeric indexes. |
Remember that flipping an array is different from reversing its element order.
Key Takeaways
array_flip()swaps array keys and values.- Original values must be strings or integers.
- Duplicate values cause earlier mappings to be overwritten.
- Numeric strings may be converted into integer keys.
- The original array remains unchanged.
- The function is useful for creating reverse lookups and mapping names to indexes.
The array_flip() function provides a simple way to reverse key-value mappings in PHP. It's especially helpful when converting lists into lookup arrays, as long as the original values are valid and sufficiently unique for your application.
For additional details, see the official PHP array_flip() documentation.