-3

I was looking at a deepflatten implementation with php and I couldn't grasp the syntax used on the 6th line.

1    function deepFlatten($items)
2    {
3        $result = [];
4        foreach ($items as $item) {
5            if (!is_array($item)) {
6                $result[] = $item;
7            } else {
8                $result = array_merge($result, deepFlatten($item));
9            }
10       }
11       return $result;
12   }
  • That's just adding `$item` into the `$result` array. You should try it, and var_dump `$result` to see, would be pretty simple :) – Adam Feb 13 '19 at 20:01
  • 3
    Is there any reason why the official documentation is not sufficient? Specifically the [Creating/modifying with square bracket syntax](http://php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying) section? – MonkeyZeus Feb 13 '19 at 20:02
  • @MonkeyZeus That comment applies to about 75% of all questions on SO. – GolezTrol Feb 13 '19 at 20:49

1 Answers1

-1

It's just adding ("pushing") an item to the end of the array. Similar to using array_push.

So, $result[] = $item; causes the array $result to be extended with an extra item. This syntax is actually described in the documentation on arrays on PHP.net as well, although searching for " [] " is not always trivial.

The deepFlatten function is a recursive function that traverses an array. If item under investigation is itself an array, deepFlatten is called recursively to return the flattened version of that sub-array, which is then merged into the result.

Because it's using either a normal push (for simple items), or array_merge (for adding the array result of the recursive call), the function would arguably more readable if array_push was used, although the effect is the same:

function deepFlatten($items)
{
    $result = [];
    foreach ($items as $item) {
        if (!is_array($item)) {
            array_push($result, $item);
        } else {
            $result = array_merge($result, deepFlatten($item));
        }
    }
    return $result;
}
GolezTrol
  • 109,399
  • 12
  • 170
  • 196