How can PHP developers effectively remove entries from an array using the foreach construct?

When using the foreach construct in PHP to iterate over an array, developers may encounter the need to remove certain entries from the array based on specific conditions. One way to achieve this is by using the unset() function within the foreach loop to remove the desired elements. It is important to note that directly modifying the array being iterated over can lead to unexpected results, so it is recommended to create a new array to store the elements that should be kept.

$array = [1, 2, 3, 4, 5];
$elements_to_remove = [2, 4];

foreach ($array as $key => $value) {
    if (in_array($value, $elements_to_remove)) {
        unset($array[$key]);
    }
}

print_r($array);