3

Unsetting elements of array in a for loop in php

Posted May 27th, 2011 in Snippets and tagged , , , , by Metod

I did something like this today:


The loop never came to the final element of the array, therefore not checking all of them. What was the problem?

Since sizeof($arr) is calculated every time the loop comes around, it was returning less and less with every unset instead of returning the same value.

Solution:


That way you ensure that size is always the correct integer. And it will run faster.

3 Responses so far.

  1. gasper_k says:

    You could also go with foreach ($arr as $i => $value) unset($arr[$i]);

  2. Metod says:

    Yes, indeed. Don’t know why that didn’t occur to me. Must be the “late” hours. 🙂

  3. Nothing wrong with using a for loop, but this is a bit neater:

    for ($i = 0, $size = sizeof($arr); $i < $size; $i++) {
    if (true) { // for sake of clarity
    unset($arr[$i]);
    }
    }