views:

54

answers:

1
$xml = simplexml_load_file($xmlPath);
$items = $xml->list->item;
...
echo $items[$currentIndex]->asXML();

When I print out $currentIndex on each iteration, I get 0, 1, 2, 3, 4, etc. When I hard code $items[0]->asXML(); $items[1]->asXML(); $items[2]->asXML(); etc. I get the data I want.

But when I loop like I do in the first code segment, it prints out items 0, 2, 4, etc.

How is that possible and what could be causing this?

Thanks, Ryan

ADDED INFO:

This is the main part of it:

$totalItems = 45;
$keepItems = 10;
$currentIndex = 0;

while($totalItems > $keepItems)
{
    $totalItems -= 1;
    print_r($xml->list->item[$currentIndex]);
    $currentIndex += 1;
}

I just tried this in a separate file and it worked in that instance:

$xml = simplexml_load_file($xmlPath);
$items = $xml->list->item;

$counter = 45;
$display = 0;

while($counter > 4)
{
    echo $items[$display]->asXML();

    $display += 1;
    $counter -= 1;
}

So something in my other code is making this happen. I will have to look at it some more as well, but it's for sure nothing obvious.

Thanks, Ryan

ADDED INFO 2:

OK, I determined the line of code that causes this "every other one" syndrome :)

unset($items[$currentIndex]);

The thought was to remove/unset an item once I used the data, but it doesn't seem to work the way I expected -- does anybody have an idea of why? Why is it unsetting something it hasn't displayed?

Thanks, Ryan

+1  A: 

Why is it unsetting something it hasn't displayed? That's not what is happening in your case. When you unset the processed item, the array-data are shift... the former element at index 1 get the index 0, 2 moves to 1 and so on. So if you access $element[1] after you have unset $element[0] you'll get the element that was at position $element[2], because the former $element[1] moved to $element[0] and $element[2] to $element[1].

If you always unset the processed element, you can do it by accessing $element[0] on each iteration an cancel if the array is empty.


// ...
while ($array) {               // same as count($array)
  $currentElement = $array[0];
  // do something
  unset($array[0]);
}
// ...
hacksteak25
Makes perfectly sense. Thank you!
Ryan S.