Home >Backend Development >PHP Tutorial >How to Flatten a Multidimensional Array in PHP?

How to Flatten a Multidimensional Array in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-05 15:37:111052browse

How to Flatten a Multidimensional Array in PHP?

Flattening Multidimensional Arrays into One Dimension

Converting a multidimensional array with numeric keys into a one-dimensional array can be a daunting task. To simplify this process, we present a reliable solution.

To flatten the multidimensional array, we utilize array_reduce() with the array_merge callback function. array_reduce() accumulates an array by iteratively applying the callback function to each element in the original array, passing along an accumulator value.

In our case, we pass the array_merge callback, which combines two arrays into a single array. The initial accumulator value is set as an empty array.

array_reduce($array, 'array_merge', array())

Here's an example to illustrate this solution:

$array = array(
    array('foo', 'bar', 'hello'),
    array('world', 'love'),
    array('stack', 'overflow', 'yep', 'man'),
);
$result = array_reduce($array, 'array_merge', array());

The resulting array, $result, will be:

array('foo', 'bar', 'hello', 'world', 'love', 'stack', 'overflow', 'yep', 'man');

This approach provides a concise and straightforward way to flatten multidimensional arrays with numeric keys into a one-dimensional structure.

The above is the detailed content of How to Flatten a Multidimensional Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn