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
$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