> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# PHP Foreach Loop

The `foreach` construct provides an iterative mechanism specifically designed for traversing arrays and objects. It abstracts internal pointer management, automatically advancing through the iterable data structure from the first element to the last until exhaustion.

## Syntax

PHP supports two syntactical forms for the `foreach` loop:

**1. Value-Only Iteration**
Assigns the value of the current element to the specified variable and advances the internal iteration state.

```php theme={"dark"}
foreach ($iterable as $value) {
    // Statement execution
}
```

**2. Key-Value Iteration**
Assigns the current element's key (index or string key) to `$key` and its value to `$value`.

```php theme={"dark"}
foreach ($iterable as $key => $value) {
    // Statement execution
}
```

## Technical Mechanics

**Type Constraints**
The `$iterable` expression must evaluate to an `array` or an `object`. When an object is provided, it can either be a standard object (which iterates over its visible properties) or an object implementing the `Traversable` interface (such as `Iterator` or `IteratorAggregate`). As of PHP 8.0, attempting to iterate over an uniterable type (such as scalar types like integers, strings, and booleans, or the special type `null`) throws a `TypeError`.

**Pass-by-Value vs. Pass-by-Reference**
By default, `foreach` operates on a copy of the iterable's values. Modifying the `$value` variable within the loop block does not mutate the original data structure.

To mutate the original array elements directly, the value variable must be prefixed with the reference operator (`&`).

```php theme={"dark"}
$array = [1, 2, 3];

foreach ($array as &$value) {
    $value = $value * 2; // Mutates the original $array in memory
}
unset($value); // Destroys the dangling reference
```

*Caveat:* The reference to the last element remains in the current scope after the loop terminates. While the PHP engine does not enforce it as a strict technical requirement, calling `unset($value)` immediately after a by-reference `foreach` loop is a highly recommended best practice to prevent unintended mutations during subsequent variable assignments.

**Internal Pointer Behavior and Modification (PHP 7+)**
In PHP 7 and later, `foreach` does not utilize or modify the array's internal pointer (which is manipulated by functions like `current()`, `next()`, or `reset()`).

The behavior of the loop when the underlying array is modified depends on the iteration mode:

* **By-Value:** `foreach` operates on a duplicated structure. If the array is modified (e.g., elements are appended or removed) within the loop, the loop continues to iterate over the original, unmodified copy.
* **By-Reference:** `foreach` operates directly on the original array. If elements are appended to the array during a by-reference loop, the loop *will* iterate over the newly added elements.

**Object Iteration**
When applied to a standard object, `foreach` iterates through all defined, non-static properties visible in the current execution scope. Iterating from outside the object exposes only `public` properties, whereas iterating from within an object's own method exposes `private` and `protected` properties.

**Array Destructuring**
If the iterable contains nested arrays, `foreach` supports array destructuring directly within the loop declaration using the `list()` construct or the short array syntax `[]`.

```php theme={"dark"}
$matrix = [[1, 2], [3, 4]];

foreach ($matrix as [$a, $b]) {
    // $a and $b represent the destructured elements of the nested arrays
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor PHP Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
