How to flatten a multidimensional array in PHP

3 Answers

0 votes
function flattenArray($array) {
    return array_reduce(
        $array,
        function ($carry, $item) {
            if (is_array($item)) {
                return array_merge($carry, flattenArray($item));
            } else {
                $carry[] = $item;
                return $carry;
            }
        },
        []
    );
}

$array = [1, [2, 3], [4, [5, 6, 7]]];

$flattenedArray = flattenArray($array);

print_r($flattenedArray);
  

  
  
/*
run:
  
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
)

*/

 



answered Dec 11, 2023 by avibootz
0 votes
function flattenArray($array) {
    $flattenedArray = [];
    
    foreach ($array as $value) {
        if (is_array($value)) {
            $flattenedArray = array_merge($flattenedArray, flattenArray($value));
        } else {
            $flattenedArray[] = $value;
        }
    }
    
    return $flattenedArray;
}

$array = [1, [2, 3], [4, [5, 6, 7]]];

$flattenedArray = flattenArray($array);

print_r($flattenedArray);
  
  
  
  
/*
run:
  
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
)

*/

 



answered Dec 11, 2023 by avibootz
0 votes
$array = [['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['h', 'i']];

$flattenedArray = array_merge(...$array);

print_r($flattenedArray);
   
   
   
   
/*
run:
   
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
    [6] => g
    [7] => h
    [8] => i
)
 
*/

 



answered Dec 14, 2023 by avibootz

Related questions

2 answers 103 views
3 answers 200 views
1 answer 207 views
1 answer 464 views
2 answers 235 views
235 views asked Jun 28, 2021 by avibootz
...