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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for the tips! This seems to have worked.. Even though i did have it outside of the for loop before :S
Why don't you unset in one go? unset($arr);
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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.