PHP array_flip Function Explained

This article explains the purpose and behavior of the array_flip() function in PHP, specifically how it exchanges the keys and values of an associative array. You will learn how the function works, how it handles duplicate values, the data type requirements for successful flipping, and see a practical code example.

The primary purpose of the array_flip() function in PHP is to swap the keys and values of an array. When you pass an associative array to this function, all the original keys become the values of the new array, and all the original values become its keys.

Basic Syntax and Example

The syntax for the function is straightforward:

array_flip(array $array): array

Here is a basic example demonstrating how the keys and values are swapped:

$original = [
    "a" => "apple",
    "b" => "banana",
    "c" => "cherry"
];

$flipped = array_flip($original);

print_r($flipped);

Output:

Array
(
    [apple] => a
    [banana] => b
    [cherry] => c
)

Important Behaviors and Constraints

When using array_flip(), there are two critical rules you must keep in mind regarding data types and duplicate values:

1. Requirements for Value Data Types

In PHP, array keys can only be integers or strings. Because array_flip() turns values into keys, the values in your original array must be either strings or integers. If a value is of an invalid type (such as an array, object, or boolean), PHP will throw a warning, and that specific key-value pair will not be included in the flipped array.

2. Handling Duplicate Values

Array keys in PHP must be unique. If your original array contains duplicate values, only the last key associated with that duplicate value will be kept. The earlier keys will be overwritten during the flipping process.

$original = [
    "first" => "apple",
    "second" => "banana",
    "third" => "apple" // Duplicate value "apple"
];

$flipped = array_flip($original);

print_r($flipped);

Output:

Array
(
    [apple] => third
    [banana] => second
)

In this case, "apple" => "first" was overwritten by "apple" => "third" because "third" was the last occurrence of the value "apple".