How to use a Loop to Remove Multiple Occurrences In PHP

If you need to remove all occurrences of a value, you can loop through the array.

Example: The loop iterates through the array, and unset() removes elements that match the specified value.

PHP
<?php
$arr = array(1, 2, 3, 4, 3, 5);
$remVal = 3;
foreach ($arr as $key => $value) {
    if ($value == $remVal) {
        // Remove the element
        unset($arr[$key]);
    }}
print_r($arr);
?>

Output
Array
(
    [0] => 1
    [1] => 2
    [3] => 4
    [5] => 5
)


Different Ways to Delete an Item From an Array in PHP

Given an array containing some elements, the task is to Delete an item from an array using PHP.

Below are the approaches to delete an item from an Array in PHP:

Table of Content

  • Using unset() Function
  • Using array_splice() Function
  • Using array_diff() Function
  • Using array_filter() Function
  • Using array_search() and unset() Functions
  • Using a Loop to Remove Multiple Occurrences

Similar Reads

Using unset() Function

The unset() function is used to remove an element from an array by its key. This function is basic and easy to use....

Using array_splice() Function

The array_splice() function removes a portion of the array and can reindex the array elements....

Using array_diff() Function

The array_diff() function compares arrays and returns the differences. This can be used to remove specific values....

Using array_filter() Function

The array_filter() function filters elements of an array using a callback function....

Using array_search() and unset() Functions

You can combine array_search() to find the index of the value and unset() to remove it....

Using a Loop to Remove Multiple Occurrences

If you need to remove all occurrences of a value, you can loop through the array....