I want to remove elements from an array with PHP and saw that it is pretty easy with array_splice
or unset
.
I would like to use this inside another function that takes this array with elements to remove as parameters. However, the function has some other return value and the array should be updated as side effect (array_splice
or unset
both work by side effect). My code looks as follows:
<?php
function removeSomeElements($arr)
{
for ($i = 0; $i<count($arr); $i++) {
$c = $arr[$i];
if ($c > 2) {
echo "Element $c found at $i\n";
unset($arr[$i]);
}
}
print_r($arr); // misses middle element
return true;
}
$t = [0, 3, 1];
print_r($t); // original array
$success = removeSomeElements($t);
print_r($t); // should be missing middle element, but everything is here
I'm experiencing the same problems with array_splice
, that is to say when I replace the call to unset
with the following:
array_splice($arr, $i, 1);
$i--;
The parameter of the function is well updated inside the function but not outside. Am I missing something?
Note: I can find a workaround for this quite easily, I just wanted to know if this is possible and why / why not. Thanks in advance!
You need to pass the array by reference &
.
Try it like this:
Replace this line:
function removeSomeElements($arr)
With this line:
function removeSomeElements(&$arr)