0

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?

ChristopherStrydom
  • 7,338
  • 5
  • 21
  • 34

2 Answers2

2

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

Ido Sarig
  • 341
  • 3
  • 11
1

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.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • Thanks a bunch! that cleared up one of my problems. I am using the Count function just so i can easily access the size of the array as it is loaded dynamically – ChristopherStrydom Oct 04 '13 at 23:56