Difference between "as $key => $value" and "as $value" in PHP foreach

Difference between "as $key => $value" and "as $value" in PHP foreach

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Difference between "as $key => $value" and "as $value" in PHP foreach loops

In many tutorials and codebases, you will see foreach loops written as foreach ($array as $key => $value). Developers often strip this down to foreach ($array as $value) because, in simple iteration scenarios, the output appears identical. When you only need to access $value['name'], discarding the key seems like a safe optimization for readability. However, removing the key variable is not merely a syntactic preference; it fundamentally changes how PHP iterates over your data and what information remains available during execution.

The core distinction lies in what PHP exposes from the internal array structure. When you use foreach ($array as $value), PHP discards the keys entirely. The loop variable $value becomes a simple value, regardless of whether the original array was indexed numerically (0, 1, 2) or associatively ('id' => '...', 'title' => '...'). This approach relies on the assumption that the specific index does not matter for your logic.

Conversely, foreach ($array as $key => $value) explicitly captures both the internal key and the value. Even if you never use $key in a conditional check like if ($key === 0), its presence alters the loop's behavior regarding array stability and memory handling. In standard PHP versions prior to 8.0, iterating with keys forces the engine to maintain a copy of the keys internally during the traversal. This can have subtle performance implications on massive datasets compared to key-less iteration, although modern JIT compilation often mitigates these differences significantly for typical application sizes.

The most critical technical difference emerges when dealing with multidimensional arrays or when you need to modify the original array in place. Consider a scenario where you are iterating over an associative array of users and need to update a specific property based on a condition that requires checking the key itself:

$data = [
    'admin' => ['role' => 'super', 'name' => 'Alice'],
    'user'  => ['role' => 'standard', 'name' => 'Bob']
];

// Key-less iteration prevents knowing which key was modified
foreach ($data as $item) {
    if ($item['role'] === 'super') {
        unset($item['role']); // Modifies a copy, not the original in some contexts
    }
}

// Key-aware iteration allows precise manipulation
foreach ($data as $key => $item) {
    if ($item['role'] === 'super') {
        unset($data[$key]['role']); // Directly modifies the specific entry
    }
}

In the first example, because the key is discarded, you lose the ability to reference $data[$key] directly for modifications. While PHP passes array elements by value in a foreach loop anyway, having the key allows you to bypass creating a new offset or relying on re-indexing logic when restructuring data. If you are building a dynamic form generator where the input name depends on the database key (e.g., input_name["{$key}"]), omitting the key renders that pattern impossible without resorting to brittle string parsing or external lookups.

Furthermore, debugging becomes significantly harder without keys. When an error occurs inside the loop, having access to $key allows you to log exactly which element triggered the exception. Without it, you are left with generic "element 5" references, making it difficult to trace issues in large lists where the index alone might not be unique across different data structures.

If you are working within a Laravel application, this distinction is especially relevant when handling collections or database results. While collect()->each() abstracts away many of these details, raw SQL queries returning arrays often retain specific keys that define relationships. For instance, if your query returns rows with explicit foreign key identifiers in the result set, iterating without capturing those keys forces you to manage state externally rather than leveraging PHP's native array navigation capabilities.

Ultimately, the decision to include $key depends on whether the index carries semantic meaning or if it is purely incidental. If you are simply rendering a list of names and the order doesn't require specific metadata from the key, as $value offers cleaner code. However, if your logic ever requires inspecting the structure, modifying the source array by offset, or debugging specific entries, retaining $key provides essential context that makes the code more robust and maintainable.

Our network