Table of Contents

16. Spread Operator in Arrays — Composing Structure With Ease

The spread operator (…) lets us merge arrays
and unpack values with clarity and intention.
It removes boilerplate and makes array composition feel natural and expressive.

It reflects a broader shift in modern PHP:
structure should be easy to build, easy to read, and free of ceremony.


1. What the Spread Operator Is

The spread operator allows us to unpack the elements of one array into another:

$all = [
    ...$defaults,
    ...$overrides,
];

No array_merge.
No function calls.
Just structure expressed directly.


2. Why Modern PHP Uses It

The spread operator reduces:

It makes arrays feel like first‑class building blocks.


3. The Mental Model

The spread operator is structural composition.

It’s not a shortcut.
It’s not syntactic sugar.
It’s a way to express how arrays come together.

The key idea:
→ To use the spread operator when
we want to compose arrays declaratively.

It turns merging into a structural expression rather than a procedural step.


4. A Simple Example

Without the spread operator:

$config = array_merge($defaults, $overrides);

With the spread operator:

$config = [
    ...$defaults,
    ...$overrides,
];

Same meaning.
More clarity.
Less ceremony.


5. When to Use the Spread Operator

Use it when:

It shines in
controllers, configuration, and any place where arrays represent structure.


6. When Not to Use the Spread Operator

Avoid it when:

The spread operator is for composition, not logic.


When AI Gets This Wrong

AI often mixes array_merge and spread syntax inconsistently, or uses the spread operator where keys collide in unexpected ways. Sometimes it spreads arrays that aren’t arrays at all, or nests spreads in ways that obscure meaning.

Our mental model helps us see when spreading expresses real structure
— and when AI is using it simply because it “looks modern”.


Summary

The spread operator lets us compose arrays with clarity and intention.
It removes ceremony, improves readability, and makes structure feel natural.

Once we internalize this,
we can immediately see when AI‑generated code:

The spread operator is a small feature
— but it teaches us
how modern PHP wants to express composition with elegance.