How to use a Loop and unset() Function In PHP

You can use a foreach loop to iterate over the elements to be removed and use unset() to remove them from the original array.

Example: This example shows the use of the above-explained approach.

PHP
<?php

// Declare an Array
$arr = [1, 2, 3, 4, 5, 6];

// Declare an array containing 
// elements that need to remove
$remove = [2, 4, 6];

// Remove elements using unset
foreach ($remove as $value) {
    if (($key = array_search($value, $arr)) !== false) {
        unset($arr[$key]);
    }
}

// Reindex the array
$arr = array_values($arr);

print_r($arr);

?>

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

Explanation:

  • $arr is the original array.
  • $remove contains the elements to be removed.
  • The foreach loop iterates over $remove, and for each element, array_search($value, $arr) finds the key, and unset($arr[$key]) removes the element.
  • array_values($arr) reindexes the array to have sequential keys.

How to Remove Multiple Elements from an Array in PHP?

Given an array containing some elements, the task is to remove some elements from the array in PHP.

Below are the approaches to remove multiple elements from an array in PHP:

Table of Content

  • Using array_diff() Function
  • Using array_filter() Function
  • Using a Loop and unset() Function
  • Using array_diff_key() Function

Similar Reads

Using array_diff() Function

The array_diff() function compares two or more arrays and returns the values in the first array that are not present in the other arrays. This is useful for removing specific elements from an array....

Using array_filter() Function

The array_filter() function filters the elements of an array using a callback function. This method allows for custom logic to determine which elements to remove....

Using a Loop and unset() Function

You can use a foreach loop to iterate over the elements to be removed and use unset() to remove them from the original array....

Using array_diff_key() Function

The array_diff_key() function compares the keys of two arrays and returns the values in the first array whose keys are not present in the second array. This method is useful when you know the keys of the elements to be removed....

Contact Us