The foreach() statement in PHP secretly makes a copy of the array and iterates that copy. This doesn't have any performance impact because it uses Copy-on-Write semantics so the array is only truly copied in memory if you write to it inside the foreach loop. Which you are doing here. So your two loops are actually iterating over 2 different copies of the $subnets array. When you unset from one array, that is not going to have any affect on the other.
The easiest way to do fix this will be to instruct PHP to NOT make the copy. Make this change in both your loops:
foreach(array() as &$row) {}
or
foreach(array() as $key => &$row) {}
That said, I do think your algorithm here could be improved. So what it seems like you're doing is:
- Iterate each subnet
- Insert
- Query for the ID of the inserted row
- Re-iterate the array and add an item to $ip_to_add that includes the ID.
My question is, what do you want the $ip_to_add to look like in the end? It seems like, right now, if there are duplicates you'll only have one insert into the table but $ip_to_add will have duplicate rows? It seems like $ip_to_add will have the same number of items as your original $subnets array? Is that what you need?
If not, what I would do is:
- De-dupe the array
- Iterate it, insert it, use mysql_insert_id() to get the ID, and add that to the array.