Alternative to foreach loop

I hope I can explain my problem well enough! I would normally use a foreach loop but I need an alternative as each entry will be displayed on a separate web page. To add to my confusion it is not an array but a DOMNodeList that I am working with. What I would have if I were not displaying each entry on a separate page is:

$items = $doc->getElementsByTagName('item');
foreach ( $items as $item ) {
  $questions = $item->getElementsByTagName('question');
  ...
}

So my query is what do I use in place of

foreach ( $items as $item ) {

Thanks G :slight_smile:

Is it like a list of items sold and each link leads to that item’s info page?

Yes, actually each item contains a question. After answering each question the user goes to the next one.

Will the user be answering the same questions in the same order or will the questions they get asked depend on what their answers were to earlier questions?

In sequential order, just like would happen with foreach.

While I’m not sure I understand why you’re accessing the DOM on the server side, if you know where you are in the array traversal (and you’re going to have to keep track of it somehow), you can just access the array directly.

In other words, use $items instead of the foreach loop. Or a range of numbers if you’re looking for more than one…

I tried

$item = $items[0];

but got an error:
Fatal error: Cannot use object of type DOMNodeList as array in …\page1.php on line 16

Try $item = $items->item(0);

Source: http://www.php.net/manual/en/domnodelist.item.php

Ah, thanks!

Dave, I didn’t understand your comment about accessing the DOM on the server side at the time. My script is ready an XML file and accessing its DOM…

The DOMNodeList object implements the Traversable interface and can be used in a foreach loop like a plain array.