Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 42 / 68

Flattening an Array

In this lesson you will learn to flatten an array with a recursive function so you can handle nested data. This is for anyone searching for "PHP flatten array".

Expanding an array that contains other arrays into one flat array is called flattening. PHP has no dedicated function for it, so you write it with recursion.

The sample code has flatten test each item with is_array($item): if it is an array it calls itself recursively and merges the result with array_merge(); otherwise it appends the value with $result[] = $item;.

A common stumbling block for beginners is that a recursive function always needs a stopping condition. Understanding that is_array() decides whether to recurse, and that the recursion stops once an item is no longer an array, keeps the behaviour predictable.

It is a useful technique whenever you want to treat nested data as one flat list. The same thinking applies when you want to collapse multi-level tree data into a single list.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)