Question

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?

Was it helpful?

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

OTHER TIPS

unset() will not reorder the array indexes if you removing an index from the middle of an numerical array. You need to reindex the array by yourself. array_values() is helpful here.

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

The Count property makes no sense for me therefore I dropped it away. You may use the function count() instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top