Search code examples
phparraysfor-loopunsetarray-unique

PHP unset Not Working as expected


I am simply trying to remove all of the Array objects that have 'visible' set to '0'

Array:

{
"Count":5,
"0":{"id":"1","visible":"0"},
"1":{"id":"3","visible":"0"},
"2":{"id":"1","visible":"0"},
"3":{"id":"2","visible":"0"},
"4":{"id":"3","visible":"0"}
}

PHP:

function cleanup($arr) {
    for($i = 0; $i < (count($arr)-1); $i++) {
        if($arr[$i]['visible'] == false) {
            unset($arr[$i]);
        }
    }
    $newarr = array_unique($arr, SORT_REGULAR);
    $newarr['Count'] = count($newarr)-1;

    return $newarr;
}

Result:

{
"Count":2,
"3":{"id":"2","visible":"0"},
"4":{"id":"3","visible":"0"}
}

In my mind this should work and return {"Count":0}. Also Why have the 'keys' not been set to 0,1 instead of 3,4. Where am i going wrong?


Solution

  • You are using count($arr)-1) inside the for loop, and it gets re-evaluated every iteration, so after you unset the first three times, i is 3, but count($arr)-1) is 1, and you exit the loop. You should set $j=count($arr)-1 before the for loop, and use for($i = 0; $i < $j; $i++)

    In general it is bad programming practice (performance-wise) to use functions like count() inside the for loop