Introduction
Flipping a two-dimensional associative array in PHP means transposing it — converting rows to columns and columns to rows. If the original array maps outer keys to inner key-value pairs, the flipped version maps inner keys to outer key-value pairs. PHP does not have a built-in array_transpose() function, so you build it by iterating through the nested array and reorganizing the keys. The array_flip() function only works on one-dimensional arrays and is not suitable for this operation.
What Flipping Means
Given a 2D array structured as a table:
1$data = [
2 'Alice' => ['math' => 90, 'science' => 85, 'english' => 92],
3 'Bob' => ['math' => 78, 'science' => 88, 'english' => 76],
4 'Carol' => ['math' => 95, 'science' => 91, 'english' => 89],
5];
Flipping (transposing) converts person → subject to subject → person:
1$flipped = [
2 'math' => ['Alice' => 90, 'Bob' => 78, 'Carol' => 95],
3 'science' => ['Alice' => 85, 'Bob' => 88, 'Carol' => 91],
4 'english' => ['Alice' => 92, 'Bob' => 76, 'Carol' => 89],
5];
Method 1: Nested foreach Loop
1$data = [
2 'Alice' => ['math' => 90, 'science' => 85, 'english' => 92],
3 'Bob' => ['math' => 78, 'science' => 88, 'english' => 76],
4 'Carol' => ['math' => 95, 'science' => 91, 'english' => 89],
5];
6
7$flipped = [];
8foreach ($data as $outerKey => $innerArray) {
9 foreach ($innerArray as $innerKey => $value) {
10 $flipped[$innerKey][$outerKey] = $value;
11 }
12}
13
14print_r($flipped);
15// Array (
16// [math] => Array ( [Alice] => 90, [Bob] => 78, [Carol] => 95 )
17// [science] => Array ( [Alice] => 85, [Bob] => 88, [Carol] => 91 )
18// [english] => Array ( [Alice] => 92, [Bob] => 76, [Carol] => 89 )
19// )
This is the most straightforward and readable approach.
Method 2: Reusable Function
1function array_transpose(array $array): array
2{
3 $result = [];
4 foreach ($array as $outerKey => $innerArray) {
5 foreach ($innerArray as $innerKey => $value) {
6 $result[$innerKey][$outerKey] = $value;
7 }
8 }
9 return $result;
10}
11
12$scores = [
13 'Q1' => ['revenue' => 1000, 'costs' => 700, 'profit' => 300],
14 'Q2' => ['revenue' => 1200, 'costs' => 750, 'profit' => 450],
15 'Q3' => ['revenue' => 1100, 'costs' => 680, 'profit' => 420],
16];
17
18$byMetric = array_transpose($scores);
19// $byMetric['revenue'] => ['Q1' => 1000, 'Q2' => 1200, 'Q3' => 1100]
Method 3: array_column (Numeric Outer Keys)
For arrays with numeric outer keys and consistent inner keys, array_column() extracts a single column:
1$users = [
2 ['name' => 'Alice', 'age' => 30, 'city' => 'NYC'],
3 ['name' => 'Bob', 'age' => 25, 'city' => 'LA'],
4 ['name' => 'Carol', 'age' => 35, 'city' => 'Chicago'],
5];
6
7// Extract a single column
8$names = array_column($users, 'name');
9// ['Alice', 'Bob', 'Carol']
10
11// Extract with a custom key
12$ageByName = array_column($users, 'age', 'name');
13// ['Alice' => 30, 'Bob' => 25, 'Carol' => 35]
14
15// Full transpose using array_column for each key
16$keys = array_keys($users[0]);
17$transposed = [];
18foreach ($keys as $key) {
19 $transposed[$key] = array_column($users, $key);
20}
21// $transposed['name'] => ['Alice', 'Bob', 'Carol']
22// $transposed['age'] => [30, 25, 35]
Method 4: array_map with Spread Operator
For numerically-indexed 2D arrays:
1$matrix = [
2 [1, 2, 3],
3 [4, 5, 6],
4 [7, 8, 9],
5];
6
7// Transpose using array_map with null callback
8$transposed = array_map(null, ...$matrix);
9
10print_r($transposed);
11// [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
This uses the special behavior of array_map(null, ...) which zips arrays together. It only works with numeric keys.
Flipping 1D Arrays with array_flip
For simple one-dimensional arrays, array_flip() swaps keys and values:
1$colors = ['r' => 'red', 'g' => 'green', 'b' => 'blue'];
2
3$flipped = array_flip($colors);
4// ['red' => 'r', 'green' => 'g', 'blue' => 'b']
array_flip() does not work on 2D arrays — it only handles scalar values.
Handling Uneven Inner Arrays
When inner arrays have different keys:
1$data = [
2 'Alice' => ['math' => 90, 'science' => 85],
3 'Bob' => ['math' => 78, 'english' => 76], // Missing 'science', has 'english'
4];
5
6$flipped = array_transpose($data);
7// [
8// 'math' => ['Alice' => 90, 'Bob' => 78],
9// 'science' => ['Alice' => 85], // Bob missing
10// 'english' => ['Bob' => 76], // Alice missing
11// ]
12
13// Fill missing values with a default
14function array_transpose_filled(array $array, $default = null): array
15{
16 $allInnerKeys = [];
17 foreach ($array as $inner) {
18 $allInnerKeys = array_merge($allInnerKeys, array_keys($inner));
19 }
20 $allInnerKeys = array_unique($allInnerKeys);
21
22 $result = [];
23 foreach ($allInnerKeys as $innerKey) {
24 foreach ($array as $outerKey => $inner) {
25 $result[$innerKey][$outerKey] = $inner[$innerKey] ?? $default;
26 }
27 }
28 return $result;
29}
Common Pitfalls
Using array_flip() on a 2D array: array_flip() only works with scalar values (strings and integers). Passing a nested array triggers a warning and produces incorrect results. Use a custom transpose function instead.
Assuming all inner arrays have the same keys: If inner arrays have different keys, some entries in the transposed result will be missing. Check for key consistency or provide a default value for missing entries.
Using array_map(null, ...$array) with associative keys: The array_map(null, ...) trick only works with numerically-indexed arrays. Associative keys are discarded during the spread operation.
Duplicate values in array_flip() for 1D arrays: When flipping a 1D array, duplicate values cause data loss because the last occurrence overwrites earlier ones. Use array_count_values() or group manually if duplicates exist.
Mutating the original array: None of these methods modify the original array — they all return new arrays. If you assign the result back to the same variable, the original data is lost.
Summary
Transpose a 2D associative array by iterating with nested foreach and swapping outer/inner keys
Use array_column() to extract specific columns from arrays of associative arrays
Use array_map(null, ...$array) to transpose numerically-indexed 2D arrays
array_flip() only works on 1D arrays with scalar values — it swaps keys and values
Handle uneven inner arrays by collecting all keys first and filling missing values with a default