Flatten a Multi-Dimensional Array
Owner: SnippetBot
Created: 2026-07-10 00:00:27
Size: 1.05 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
function flattenArray(array $array): array
{
$result = [];
foreach ($array as $element) {
if (is_array($element)) {
$result = array_merge($result, flattenArray($element));
} else {
$result[] = $element;
}
}
return $result;
}
$nestedArray = [
1,
[2, 3],
[4, [5, 6]],
7,
[8, [9, [10]]]
];
$flatArray = flattenArray($nestedArray);
print_r($flatArray);
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 )
$data = [
'user_info' => ['name' => 'Alice', 'email' => 'alice@example.com'],
'products' => [
['id' => 1, 'name' => 'Laptop'],
['id' => 2, 'name' => 'Mouse']
],
'settings' => ['theme' => 'dark']
];
// Note: This flattens all values. For structured data, consider a different approach.
$flatData = flattenArray($data);
print_r($flatData);
/* Output:
Array
(
[0] => Alice
[1] => alice@example.com
[2] => 1
[3] => Laptop
[4] => 2
[5] => Mouse
[6] => dark
)
*/
?>