This article demonstrates how to remove an array element in a foreach loop in PHP.

1. Using unset() function

You can easily remove an element from an array with the help of the unset() function. The following solution demonstrates its usage by iterating over an associative array using a foreach loop and unsetting the array element that matches the given key.

Download  Run Code

Output:

Array
(
  [key1] => value1
  [key3] => value3
)

 
Here’s another example demonstrating the usage of the unset() function. It iterates over the array of arrays using a nested foreach loop and removes the array element that matches the given key-value pair.

Download  Run Code

Output:

Array
(
  [0] => Array
    (
      [name] => Jason
      [age] => 20
    )

  [2] => Array
    (
      [name] => Andy
      [age] => 15
    )
)

2. Using array_splice() function

Alternatively, you may use the array_splice() function to remove a specified portion of an array in a foreach loop. For example, the following code removes a specific item from the array of arrays using the array_splice() function.

Download  Run Code

Output:

Array
(
  [0] => Array
    (
      [name] => Jason
      [age] => 20
    )

  [2] => Array
    (
      [name] => Andy
      [age] => 15
    )
)

3. Using array_filter() function

Before PHP 7, the foreach used the internal array pointer for looping, and this may lead to unexpected behaviour if array keys are removed within a loop. A better solution is to use the array_filter() function, which doesn’t risk non-deterministic behaviour later. The array_filter() function accepts a callback function and conditionally removes array elements that satisfy the predicate, as shown below:

Download  Run Code

Output:

Array
(
  [key1] => value1
  [key3] => value3
)

 
Note that the default parameter to the callback is an array value. If you’d rather have the key passed to the callback instead of the value, use the ARRAY_FILTER_USE_KEY option. Similarly, to have both value and key passed to the callback, you can use the ARRAY_FILTER_USE_BOTH option.

That’s all about removing an array element in a foreach loop in PHP.