When is an array not an array?



Hi, folks.

I've encountered what seems to me to be something of an oddity while playing
around with XML parsing in PHP, and I wondered if any of you might be able
to clear up my confusion...

Here's a little code:

$xmlDoc = new DOMDocument();
$xmlDoc->load('widget_data.xml');
$widgets = $xmlDoc->getElementsByTagName('widget');

My understanding was that '$widgets' is an array of elements, and the
following 'foreach' iterates through that array (this works):

foreach ($widgets as $widget)
{
....
}

However, I get an error if I try to access '$widgets' using square-brackets,
e.g.:

$widget = $widgets[0];

(The error is: "Fatal error: Cannot use object of type DOMNodeList as
array".)

PHP confirms that the first element of the 'array' has an index/key of '0'
with the following (or similar), but won't let me access it directly using
'$widgets[0]':

foreach ($widgets as $key => $widget)
{
echo("<p>" . $key . "</p>\n");
}

Does anyone have an explanation as to why a DOMNodeList can be accessed like
an array using 'foreach', but won't allow square-brackets to be used? What
exactly *is* a DOMNodeList?

Thanks for any help.

A.

PS. I am aware that DOMNodeLists have an 'item()' method with which nodes
within the list can be referred to via index, but my confusion still stands
as to why I can't simply use '[]'s.


.



Relevant Pages

  • Re: [PHP] foreach() using current() strange beahvior
    ... that's expected as foreach moves the internal array pointer, ... When using the internal pointer just by calling current(so not moving ... Unless the array is referenced, foreach operates on a copy of the ...
    (php.general)
  • Re: safe to delete elements of array in foreach
    ... I agree with Jon on this one. ... I make it a habit not to delete entries in a foreach() loop. ... build an array of keys I want to delete, and after the loop ends, delete ... I don't know whether an operation like this is guaranteed to work in PHP ...
    (comp.lang.php)
  • Re: safe to delete elements of array in foreach
    ... (normally this is not the case but not sure in php) ... I make it a habit not to delete entries in a foreach() loop. ... build an array of keys I want to delete, and after the loop ends, ...
    (comp.lang.php)
  • Re: safe to delete elements of array in foreach
    ... I agree with Jon on this one. ... I make it a habit not to delete entries in a foreach() loop. ... build an array of keys I want to delete, and after the loop ends, delete ... I don't know whether an operation like this is guaranteed to work in PHP ...
    (comp.lang.php)
  • Re: When is an array not an array?
    ... My understanding was that '$widgets' is an array of elements, ... can use it in a foreach loop. ... I am aware that DOMNodeLists have an 'item' method with which nodes ... PHP doesn't support overloading operators, which I believe would be required ...
    (comp.lang.php)