John Sonderson
John Sonderson

Reputation: 3388

Difference between SimpleXMLElement PHP for and foreach loops?

I would like to know whether in PHP 5.6.11 there is any difference between the following two ways of iterating with SimpleXMLElement:

$simpleXMLIterator = new SimpleXMLIterator($xmlCode);

foreach ($simpleXMLIterator as $xmlElement) {

  echo $xmlElement->getName(), "\n";

}

and

$simpleXMLIterator = new SimpleXMLIterator($xmlCode);

for ($simpleXMLIterator->rewind(); $simpleXMLIterator->valid(); $simpleXMLIterator->next()) {

 echo $simpleXMLIterator->current()->getName(), "\n";

}

Upvotes: 1

Views: 186

Answers (1)

ThW
ThW

Reputation: 19502

It will call the same logic inside the object. Iterator is an interface that you can implement into your own objects. The interface specifies methods like rewind(), next(), current(), ...

If you implement the interface the object can be used with foreach(). foreach() recognizes the interface and calls the methods.

SimpleXMLIterator implements that interface, more specific it implements RecursiveIterator which extends Iterator with two methods (hasChildren() and getChildren() to handle recursive structures.

Upvotes: 1

Related Questions