Search code examples
phpfor-loopunset

PHP for not loop for all values


I have this code snippet:

var_dump(count($xml)); // returns 34 

for($i = 8; $i < count($xml); $i++){ 
    echo "unseting $i <br>";
    unset($xml[$i]);
}

var_dump($xml);

Result:

int 34

unseting 8 unseting 9 unseting 10 unseting 11 unseting 12 unseting 13 unseting 14 unseting 15 unseting 16 unseting 17 unseting 18 unseting 19 unseting 20

Why is this for breaked at $i = 20 ?

When i change for-loop for $i = 0 - it's still works anomaly. I get only number 0-16 - simply always only half. But when i comment unset line - then it's iterate over all values..

Where can be problem in unset? Why unset breaking my for at half?


Solution

  • You'r experiencing this because unset() destroys the specified variables.

    So when you iterate over the loop and at the same time you're using unset() to remove the element from array, array size also decreases along with removing elements from array,

    So execution goes like this,

    unseting 8 with remaining array size: 34 
    unseting 9 with remaining array size: 33 
    unseting 10 with remaining array size: 32 
    unseting 11 with remaining array size: 31 
    unseting 12 with remaining array size: 30 
    unseting 13 with remaining array size: 29 
    unseting 14 with remaining array size: 28 
    unseting 15 with remaining array size: 27 
    unseting 16 with remaining array size: 26 
    unseting 17 with remaining array size: 25 
    unseting 18 with remaining array size: 24 
    unseting 19 with remaining array size: 23 
    unseting 20 with remaining array size: 22 
    

    Demo: https://eval.in/599426