Convert multidimensional array into single array
If you want to flatten a multi-dimensional array in PHP, you can either use a custom function or use the array_merge
function in combination with the ...
(splat) operator. Here's an example using array_merge
and ...
operator:
Here is an example of how you can use array_merge
function in combination with the ...
(splat) operator>:
<?php
$multi_dimensional_array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']];
$single_array = array_merge(...$multi_dimensional_array);
print_r($single_array);
The output of the above code will be:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f [6] => g [7] => h [8] => i )
In this example, the ...
(splat) operator is used to spread the sub-arrays of $multi_dimensional_array
as separate arguments to the array_merge
function, which concatenates them into a single array. The resulting $single_array
contains all the elements of the sub-arrays, flattened into a single array.
Alternatively, if you want to use a custom function to flatten a multi-dimensional array, you can define one like this:
<?php
function array_flatten($array)
{
$result = [];
foreach ($array as $element) {
if (is_array($element)) {
$result = array_merge($result, array_flatten($element));
} else {
$result[] = $element;
}
}
return $result;
}
$multi_dimensional_array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']];
print_r(array_flatten($multi_dimensional_array));
This custom function recursively flattens a multi-dimensional array by checking each element to see if it is an array, and if so, recursively flattening that array as well. If the element is not an array, it is added to the result array. Once all elements have been processed, the result array is returned.