Current Location: Home> Latest Articles> array_flip() What happens when a duplicate value is encountered?

array_flip() What happens when a duplicate value is encountered?

M66 2025-05-14

In PHP, array_flip() is a very practical function, and its function is to put arrays in. In other words, the original value will become a new key, and the original key will become a new value.

But the question is: What if there are duplicate values ​​in the original array? How will array_flip() be handled? Will the previous value be overwritten? This article will analyze this issue in detail.

Basic usage of array_flip()

Let’s take a look at a basic example:

 $input = [
    'a' => 1,
    'b' => 2,
    'c' => 3
];

$flipped = array_flip($input);
print_r($flipped);

Output result:

 Array
(
    [1] => a
    [2] => b
    [3] => c
)

This is OK, because the values ​​are unique and can be safely used as keys.

Repeat value situation

Let's look at another example, this time with a duplicate value:

 $input = [
    'first'  => 'apple',
    'second' => 'banana',
    'third'  => 'apple'
];

$flipped = array_flip($input);
print_r($flipped);

Output result:

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

As you can see, the key 'first' => 'apple' is overwritten by 'third' => 'apple' after flip. That is to say, array_flip() will use the last occurrence value as the final key , and the previous same-value items will be ignored (overridden).

This should be paid special attention when processing big data to avoid accidental loss of data.

Practical application scenarios

Suppose you are developing a tag system, with each tag ID corresponding to a tag name:

 $tags = [
    1 => 'php',
    2 => 'javascript',
    3 => 'php'
];

$flipped = array_flip($tags);

You may want to back-check the ID by tag name, but at this time 'php' will only retain one ID ( 3 ) and ID 1 will be overwritten. To handle this situation safely, you may need to use other methods, such as manual traversal:

 $reverse = [];
foreach ($tags as $id => $name) {
    $reverse[$name][] = $id;
}

This allows all IDs to be retained and becomes a many-to-one relationship.

Tips: Pay attention to the legality of keys

Since the keys of an array in PHP must be integers or strings , if the value is an array, object, or null , etc. that cannot be used as a key, array_flip() will throw a warning:

 $input = [
    'a' => null,
    'b' => ['nested']
];

$flipped = array_flip($input); // Will report an error

Summarize

  • array_flip() will take the value as the key and the key as the value.

  • When a duplicate value is encountered, the front will be overwritten by the back.

  • To avoid data loss, consider using more flexible processing methods such as grouping.

  • Note that the value must be of the type that can be used as a key.