This question already has an answer here:
I have a foreach loop where I want to unset an item from an array if certain conditions are met, like this:
foreach ($array as $element) {
if (conditions) {
unset($element);
}
}
But the element is not unset after that. What am I doing wrong? Am I unsetting a reference to the actual element or something like that?
</div>
Simple Solution, unset the element by it's index:
foreach ($array as $key => $element) {
if (conditions) {
unset($array[$key]);
}
}
Just unsetting $element
will not work, because this variable is not a reference to the arrays element, but a copy. Accordingly changing the value of $element
will not change the array too.
An alternate method, you can pass the array element into the loop by reference by doing the following:
foreach($array as &$var) {
unset($var);
}
This is useful because you then have direct access to the array element to change or delete as you wish without having to construct a new array or accessing by key. Any changes you make to $var affects the contents of $array.