为数组赋值,将索引留空时会发生什么? [重复]

This question already has an answer here:

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   }
</div>

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;
}