Home >Backend Development >PHP Tutorial >How Can I Flatten a Multidimensional Array in PHP Without Recursion?

How Can I Flatten a Multidimensional Array in PHP Without Recursion?

Linda Hamilton
Linda HamiltonOriginal
2024-12-27 15:45:14911browse

How Can I Flatten a Multidimensional Array in PHP Without Recursion?

Flattening Multidimensional Arrays in PHP

Flattening a multidimensional array involves converting its nested structure into a one-dimensional array. This can be achieved in PHP without using recursion or references.

Iterative Solution Using array_walk_recursive()

For PHP versions 5.3 and higher, the most concise solution is to use array_walk_recursive() along with the new closures syntax:

function flatten(array $array) {
    $return = array();
    array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
    return $return;
}

This function traverses the array recursively, storing each encountered value in the $return array. The result is a flattened one-dimensional array containing all the original values.

The above is the detailed content of How Can I Flatten a Multidimensional Array in PHP Without Recursion?. 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