I have an array, wich has about millions of keys. But some of them are equal to "DEL", which I want to unset:
$array = array ("something1", "something2", "DEL", ... , "DEL", "DEL", "something else", "something else n");
I want to unset these keys with "DEL" from an array, but its maybe bug, it doesn't delete these values from an array. Whats the problem?
here is the code:
<?php
$array = {"sfsff", "DEL", ... "DEL", "bcbcgh"};
for ($i=0; $i<sizeof($array); $i++)
{
if ($array[$i] == "DEL")
{
unset($array[$i]);
}
}
var_dump($array);
?>
and here, var dump prints me out the non changed array. Whats the problem?
Try changing:
$array = {"sfsff", "DEL", "DEL", "bcbcgh"}; // Invalid array input
to
$array = ["sfsff", "DEL", "DEL", "bcbcgh"]; // this is an array
From the code you shared via email, it is breaking the for
loop after a few thousand iterations(45K in my case) because of memory issues. The reason is you are calculating the size of the array with every single iteration for ($i=0; $i < sizeof($array); $i++)
and that is not at all a good solution while working with loops. You need to change your code to:
$length = count($newarray); // calculate the count first and then use it in the loop.
for ($i=0; $i < $length; $i++)
{
if ($newarray[$i] == "DEL") {
unset($newarray[$i]);
}
}
Here, with our $length
variable holding the size of the array, we don't make our application to check the length/count each time it loops. Also, I have used count()
instead of sizeof()
because count()
takes less time to calculate the size of an array.
According to one benchmark, using a pre-calculated variable instead of forcing the count each loop can be 94% faster. That can quickly add up. Please refer to section Counting LoopsFor-loop test on the same page. You can also see the time difference taken in case of
count()
andsizeof()
.
I hope this helps.
array_filter(["sfsff", "DEL", "DEL", "bcbcgh"],function($value) {
return $value != "DEL";
});