Home >Backend Development >PHP Tutorial >How Can I Flatten a Multidimensional Numeric-Keyed Array in PHP?

How Can I Flatten a Multidimensional Numeric-Keyed Array in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-12-02 02:54:09866browse

How Can I Flatten a Multidimensional Numeric-Keyed Array in PHP?

Flattening Multidimensional Arrays into One Dimension

Transforming a multidimensional array into a one-dimensional array can present a challenge, especially when the original array contains only numeric keys. Unlike other approaches that accommodate varying keys, this question specifically addresses the need for flattening multidimensional arrays with simple numeric keys.

Solution:

The solution to this problem lies in utilizing the array_reduce() function along with array_merge() and an empty array as the initial argument. This effectively combines all the sub-arrays recursively into a single flattened array.

Code:

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

Explanation:

  • array_reduce() iteratively applies a user-defined function (array_merge in this case) to the elements of the array, together with the specified initial value (array()).
  • array_merge merges the current element (a sub-array) with the flattened result obtained thus far.
  • The empty array as the initial argument serves as the starting point for the recursive merging process.

Example:

Consider the following multidimensional array:

$array = array(
    array(1, 2, 3),
    array(4, 5, 6)
);

Applying the flattening solution:

$flattenedArray = array_reduce($array, 'array_merge', array());

The resulting $flattenedArray will be:

array(1, 2, 3, 4, 5, 6)

The above is the detailed content of How Can I Flatten a Multidimensional Numeric-Keyed 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