Search code examples
phpdomdocumentarray-walk

PHP Why does array_walk not work with DOMDocument::getElementsByTagName


just wondering why the following code doesn't itterate through
DOMDocument::getElementsByTagName

<?php
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadHTML('<html><head>...blablabla...</html>');
$elements = $dom->getElementsByTagName('div');
array_walk($elements, 'var_dump'); // doesn't work ?>

But the following code does work:

<?php
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadHTML('<html><head>...blablabla...</html>');
$elements = $dom->getElementsByTagName('div');
foreach($elements as $element) {
  var_dump($element); // does work
} ?>

Solution

  • The return value from getElementsByTagName() is a DOMNodeList object, not an array: a DOMNodeList object is Traversable, so a foreach() will iterate over it; but array_walk() requires an actual array argument, so it can't be used with array_walk().

    Calling array_walk() with an argument that isn't an array won't generate an Error, but it will generate a Warning, and it will return a result of boolean false.