Last active
June 23, 2025 22:16
-
-
Save SeanCannon/6585889 to your computer and use it in GitHub Desktop.
PHP array_flatten() function. Convert a multi-dimensional array into a single-dimensional array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Convert a multi-dimensional array into a single-dimensional array. | |
* @author Sean Cannon, LitmusBox.com | [email protected] | |
* @param array $array The multi-dimensional array. | |
* @return array | |
*/ | |
function array_flatten($array) { | |
if (!is_array($array)) { | |
return false; | |
} | |
$result = array(); | |
foreach ($array as $key => $value) { | |
if (is_array($value)) { | |
$result = array_merge($result, array_flatten($value)); | |
} else { | |
$result = array_merge($result, array($key => $value)); | |
} | |
} | |
return $result; | |
} |
Using variadic:
$result = array_merge(...$array);
As was previously stated, this doesn't work for associative arrays, but if you really don't care about the keys, you can try this:
array_merge(...array_values($array))
Tested on PHP 8.2.8
for my task i was needed function for flatten multidimensional array but i also needed keep keys like values, so i add little changes for initial answer and get what i needed
function array_flatten($array) {
if (!is_array($array)) {
return false;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
//just add [$key]
$result = array_merge($result, [$key], array_flatten($value));
} else {
$result = array_merge($result, array($key => $value));
}
}
return $result;
}
$etalonMap = [
'OneItem' => [
'item_1' => [
'item_1_1',
'item_1_2',
'item_1_3'
],
'item_2',
'item_3',
'item_4',
'item_5',
],
'TwoItem'=> [
'TwoItem_1',
]
];
print_r(array_flatten($etalonMap));
/**
* Array
(
[0] => OneItem
[1] => item_1
[2] => item_1_1
[3] => item_1_2
[4] => item_1_3
[5] => item_2
[6] => item_3
[7] => item_4
[8] => item_5
[9] => TwoItem
[10] => TwoItem_1
)
**/
``
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For a simple 2D array: