How to remove an array element in a foreach loop?

Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable. The behavior of this function depends on different things. If the function is called from inside of any user defined function then it unsets the value associated with the variables inside it, leaving the value which is initialized outside it.

Syntax:

unset( $variable )

Return Value:

This function does not returns any value. Below examples use unset() function to remove an array element in foreach loop.

Example 1:

php
<?php

// Declare an array and initialize it
$Array = array(
    "w3wiki_1", 
    "w3wiki_2", 
    "w3wiki_3"
);

// Display the array elements
print_r($Array);

// Use foreach loop to remove array element
foreach($Array as $k => $val) {
    if($val == "w3wiki_3") {
        unset($Array[$k]);
    }
}

// Display the array elements
print_r($Array);

?>

Output
Array
(
    [0] => w3wiki_1
    [1] => w3wiki_2
    [2] => w3wiki_3
)
Array
(
    [0] => w3wiki_1
    [1] => w3wiki_2
)

Example 2:

php
<?php

// Declare an array and initialize it
$Array = array(
    array(0 => 1),
    array(4 => 10),
    array(6 => 100)
);

// Display the array elements
print_r($Array);

// Use foreach loop to remove 
// array element
foreach($Array as $k => $val) {
    if(key($val) > 5) {
        unset($Array[$k]);
    }
}

// Display the array elements
print_r($Array);

?>

Output
Array
(
    [0] => Array
        (
            [0] => 1
        )

    [1] => Array
        (
            [4] => 10
        )

    [2] => Array
        (
            [6] => 100
        )

)
Array
(
    [0] => Array
        (
            [0] => 1
        )

    [1] => Array
        (
            [4] => 10
        )

)

Example 3: Using a Temporary Array

Instead of directly modifying the array while iterating, you can use a temporary array to store elements that should not be removed. This approach avoids issues with modifying the array during iteration.

PHP
<?php
// Nikunj Sonigara
// Declare an array and initialize it
$Array = array( 
    "w3wiki_1",  
    "w3wiki_2",  
    "w3wiki_3"
);

// Display the array elements
print_r($Array);

$tempArray = array(); // Temporary array to store elements that should not be removed

// Use foreach loop to check and remove elements
foreach($Array as $val) { 
    if($val != "w3wiki_3") { 
        $tempArray[] = $val;
    } 
}

// Assign the temporary array back to the original array
$Array = $tempArray;

// Display the array elements
print_r($Array);

?>

Output
Array
(
    [0] => w3wiki_1
    [1] => w3wiki_2
    [2] => w3wiki_3
)
Array
(
    [0] => w3wiki_1
    [1] => w3wiki_2
)

Contact Us