What are the potential pitfalls of using unset() in a foreach loop to remove array elements in PHP?

Using unset() in a foreach loop to remove array elements in PHP can lead to unexpected behavior because it can modify the array being iterated over, causing elements to be skipped or the loop to terminate prematurely. To avoid this issue, it is recommended to collect the keys of the elements to be removed first and then unset them outside of the loop.

$keysToRemove = array();
foreach ($array as $key => $value) {
    if ($value === 'value_to_remove') {
        $keysToRemove[] = $key;
    }
}

foreach ($keysToRemove as $key) {
    unset($array[$key]);
}