How to flatten a multidimensional array with PHP?

Spread the love

Sometimes, we want to flatten a multidimensional array with PHP.

In this article, we’ll look at how to flatten a multidimensional array with PHP.

How to flatten a multidimensional array with PHP?

To flatten a multidimensional array with PHP, we call array_merge with all the nested arrays that want to flatten.

For instance, we write

$flattened = array_merge(...$a);

to call array_merge with the nested arrays in the $a array to merge the nested array into a single array and return it.

... unpacks the nested arrays as arguments of array_merge.

Conclusion

To flatten a multidimensional array with PHP, we call array_merge with all the nested arrays that want to flatten.

Leave a Reply

Your email address will not be published. Required fields are marked *