Skip to main content

Remove an Array Element in a foreach Loop in PHP

When working with arrays in PHP, there may be times when you need to delete an element from within a loop. For example, if you have an array of user data and you want to remove a user from the array, you would use a foreach loop to delete the element.

There are a few reasons why you might need to delete an element while looping. One reason is that you may no longer need the element and want to free up some space in the array. Another reason is that you may have a corrupted or invalid element in the array and need to delete it to keep the array functioning properly.

Whatever the reason, deleting an element while looping is a fairly simple process. All you need to do is access the array index of the element that you want to delete and then use the PHP unset() function to delete it.

The unset() function will destroy the specified variable.

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
foreach ($arr as $key => $value) {
    if ($value % 2 == 0) {
        unset($arr['$key']);
    }
}
$removedScores = [];
foreach($scores as $k => $score){
    if($score->total == 0){
        $removedScores[] = $score;
        unset($scores[$k]);
    }
}
foreach($removedScores as $score){
    //do something here
}

By continuing to use the site, you agree to the use of cookies.