Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_flip() function

Reference for PHP array_flip(): swap keys and values, handle duplicate values and invalid value types, and use flipped arrays for fast lookups.

array_flip() exchanges the keys and values of an array: each value becomes a key and each key becomes the value. Only integers and strings can be array keys, so only those two types are allowed as values.

If several elements have the same value, they collide on the same new key and only the last one survives. That makes the function lossy, but also handy for fast membership tests and for removing duplicates.

PHP
<?php
print_r(array_flip(["a" => 1, "b" => 2])); // [1 => "a", 2 => "b"]

Try it

PHP Swapping and collisions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Fast lookups and unique values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_flip(array $array): array
Name Description
$array An array whose values are all integers or strings.

Return value: the flipped array. Values of other types are skipped, each with a warning ("Can only flip string and integer values, entry skipped").

Usage notes

  • Collisions lose data. When two values are equal, the later key replaces the earlier one.
  • Numeric strings become integer keys. The value "5" turns into the key 5, as with any array key.
  • Fast membership test: isset($flipped[$x]) is faster than in_array() on long lists, because it uses a hash lookup. Build the flipped array once, reuse it many times.
  • Distinct values: array_keys(array_flip($a)) returns each value once, in order of first appearance. array_unique() does the same but keeps the original keys.
  • Not for nested data. Arrays, floats, booleans and null as values are skipped.
  • Related reversal: array_reverse() changes order, not the key/value roles; array_combine() builds an array from separate keys and values.