How to delete object from array inside foreach loop?

How to delete object from array inside foreach loop?

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

Stefan Bogdanescu

Founder & Senior Architect

Why unset Fails Inside a foreach Loop and How to Fix It

Attempting to remove an element from an array while iterating over it using a standard foreach loop is one of the most persistent bugs in PHP development. You might be tempted to use unset directly inside the loop condition, hoping the array structure updates immediately. However, the language runtime maintains a specific state for the iteration pointer that prevents this behavior.

In your scenario, you are iterating through an array of objects ($array) and trying to drop an item based on an 'id' property. The code snippet you provided attempts to unset the current $element or even the entire $array. Neither approach works as intended because foreach decouples the loop's internal counter from the actual length of the array being traversed.

When you execute unset($element), you are effectively removing the object at the current index. However, the foreach construct does not automatically adjust its internal cursor. The next iteration will still attempt to read the value that was just deleted, often resulting in a notice about undefined offsets or simply skipping logic because the pointer gets out of sync with the remaining data.

The fundamental issue is that foreach relies on the array's count at the start of each cycle. If you modify the array structure (adding or removing items) during iteration, the loop becomes unreliable. Unsetting an item shifts subsequent elements down in memory, but the internal index maintained by the loop engine remains fixed for the next step, leading to unpredictable behavior where you might miss elements or crash the script.

The Correct Approach: Collect Indices First

The most robust solution is to separate the identification of the target data from the modification of the container. Instead of trying to delete on the fly, build a list of keys that need removal before executing any deletions. This ensures the loop completes its read phase without interference from write operations.

Here is how you can refactor your logic:

$keysToDelete = [];

foreach ($array as $key => $element) {
    // Check if the object matches the criteria
    if (isset($element['id']) && $element['id'] === 'searched_value') {
        $keysToDelete[] = $key;
    }
}

// Now remove the items in a separate pass
foreach ($keysToDelete as $key) {
    unset($array[$key]);
}

By collecting indices first, you guarantee that every element is evaluated exactly once against your condition. The subsequent unset operations happen after the reading loop has finished, ensuring data integrity. This pattern scales well even if you need to remove multiple items or perform complex validation logic before deletion.

Using array_filter for Functional Style

If you prefer a functional programming approach, array_filter is often more concise and less prone to off-by-one errors. It handles the iteration internally and returns a new array containing only the elements that pass the test callback.

$array = array_filter($array, function ($element) {
    // Return false if this element should be removed
    return !isset($element['id']) || $element['id'] !== 'searched_value';
});

This method creates a fresh copy of the array excluding the unwanted objects. While it uses more memory for large datasets due to the temporary copy, the code is significantly cleaner and easier to reason about. If you are working in an environment where memory is not a constraint or if you are using Laravel's collection facade (which wraps arrays), this approach is highly recommended because collections implement filter natively without manual copying.

Performance Considerations

When deciding between the two methods, consider your dataset size. The "collect keys first" method modifies the original array in place and is generally more memory-efficient for massive datasets. Conversely, array_filter creates a new array structure. If you are processing millions of records, the overhead of creating a new array might be noticeable, making the index-collecting pattern preferable.

However, if you are working within the Laravel ecosystem, remember that collections abstract these details away. You can chain methods like filter() and pluck() to build readable pipelines without worrying about internal array pointers. For raw arrays, sticking to the separation of concerns—read, then write—is the industry standard for maintaining stability.

Our network