array_flip

array_flip(array $array): array

Swaps keys with values in an array (on duplicate values the later key wins).

C C23

C23
#include <stdio.h>

int main(void) {
    const char *keys[] = {"a", "b"};
    int values[] = {1, 2};
    for (int i = 0; i < 2; i++) {
        printf("\"%d\":\"%s\"%s", values[i], keys[i], i + 1 < 2 ? "," : "\n");
    }
    return 0;
}
Output
"1":"a","2":"b"

C++ C++26

C++26
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> m{{"a", 1}, {"b", 2}};
    std::map<int, std::string> flipped;
    for (const auto &[k, v] : m) {
        flipped[v] = k; // later writes to an equal key overwrite earlier ones
    }
    bool first = true;
    for (const auto &[v, k] : flipped) {
        if (!first) std::cout << " ";
        first = false;
        std::cout << v << "->" << k;
    }
    std::cout << "\n";
    return 0;
}
Output
1->a 2->b

C# v11.0.100

v11.0.100
var m = new Dictionary<string, int> { ["a"] = 1, ["b"] = 2 };
var flipped = m.ToDictionary(kv => kv.Value, kv => kv.Key);
Console.WriteLine(string.Join(" ", flipped.Select(kv => $"{kv.Key}->{kv.Value}")));
Output
1->a 2->b

Go v1.27.4

v1.27.4
package main

import "fmt"

func main() {
	m := map[string]int{"a": 1, "b": 2}
	flipped := map[int]string{}
	for k, v := range m {
		flipped[v] = k
	}
	fmt.Println(flipped[1], flipped[2]) // map iteration is unordered; read known values back to keep output stable
}
Output
a b

Java v27.0.1

v27.0.1
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> m = new LinkedHashMap<>();
        m.put("a", 1);
        m.put("b", 2);
        Map<Integer, String> flipped = new LinkedHashMap<>(); // LinkedHashMap keeps insertion order so the output is reproducible
        for (var e : m.entrySet()) {
            flipped.put(e.getValue(), e.getKey());
        }
        System.out.println(flipped);
    }
}
Output
{1=a, 2=b}

JavaScript v26.13.1

v26.13.1
const m = { a: 1, b: 2 };
const flipped = Object.fromEntries(
  Object.entries(m).map(([k, v]) => [v, k])
);
console.log(flipped);
Output
{ '1': 'a', '2': 'b' }

PHP v8.6.0

v8.6.0
echo json_encode(array_flip(["a" => 1, "b" => 2])), "\n",
     json_encode(array_flip(["x" => 1, "y" => 1]));
Output
{"1":"a","2":"b"}
{"1":"y"}

Python v3.15.2

v3.15.2
m = {"a": 1, "b": 2}
print({v: k for k, v in m.items()})
Output
{1: 'a', 2: 'b'}

Rust v1.99.1

v1.99.1
use std::collections::BTreeMap;

fn main() {
    let m = BTreeMap::from([("a", 1), ("b", 2)]);
    // BTreeMap keeps key order so output is reproducible (HashMap iterates unordered)
    let flipped: BTreeMap<i32, &str> = m.iter().map(|(k, v)| (*v, *k)).collect();
    println!("{:?}", flipped);
}
Output
{1: "a", 2: "b"}

TypeScript v26.13.1

v26.13.1
const m: Record<string, number> = { a: 1, b: 2 };
const flipped: Record<string, string> = Object.fromEntries(
  Object.entries(m).map(([k, v]) => [v, k])
);
console.log(flipped);
Output
{ '1': 'a', '2': 'b' }

Language differences

C: no built-in map container — parallel arrays demonstrate the key/value swap (example); real code builds a hash table or reverse-scans by value.

C++: a manual loop filling a std::map (example); the value type must qualify as a key (comparable); later writes overwrite earlier ones for equal values, matching PHP flip.

C#: LINQ ToDictionary(kv => kv.Value, kv => kv.Key) (example); duplicate values throw ArgumentException outright (unlike PHP's silent overwrite).

Go: a hand-written inversion loop (example); note map iteration is unordered — the example reads known keys back to keep the output order stable; equal values likewise overwrite.

Java: LinkedHashMap preserves insertion order so the output is reproducible (example); a HashMap version prints in unstable order; Collectors.toMap throws on duplicates unless given a merge function.

JavaScript: Object.fromEntries over entries (example); object keys are stringified — numeric values become "1", matching PHP's numeric-key semantics.

PHP: values must be usable as keys (int/string); on duplicates the later key wins (second line of the example: {"1":"y"}); illegal value types (arrays/objects) are silently dropped.

Python: the dict comprehension {v: k for k, v in m.items()} (example); key types are unconstrained (1 and "1" are distinct keys); later writes overwrite on duplicates.

Rust: BTreeMap keeps the output reproducible (the example comment spells out HashMap's unordered iteration); collect() into BTreeMap<i32, &str> overwrites on equal values.

TypeScript: same as JavaScript; the reversed Record needs an explicit annotation (example).