Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using unset() function in an array to delete elements

Tags:

arrays

php

unset

Trying to delete all elements in the array (given below) which are less then 0 using the following code:

 <?php 
       $arr=array(1,2,3,4,5,-6,-7,-8,-9,-10);

        for ($i=0;$i<count($arr);$i++){
                if ($arr[$i]<0) {
                unset($arr[$i]);
                }
        }

    var_dump($arr);

    echo '<pre>', print_r($arr), '</pre>';

    ?>

However, the result is the following:

array(7) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [8]=> int(-9) [9]=> int(-10) }
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [8] => -9
    [9] => -10
)
1

Quite confused why not all the elements which are less then 0 are removed from the array. Any thoughts on this?

like image 873
Sam Avatar asked Dec 03 '22 11:12

Sam


1 Answers

This is what usually happens when you remove elements while iterating forwards through a collection. You end up missing elements because you're trying to iterate a moving target. One solution would be to iterate backwards

for ($i = count($arr) - 1; $i >= 0; $i--)

Another would be to simply use array_filter to create a new array

$newArr = array_filter($arr, function($num) {
    return $num >= 0;
});
like image 94
Phil Avatar answered Dec 18 '22 17:12

Phil