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
Release: 2024-12-27 15:45:14
Original
874 people have browsed it

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template