What is the difference between using foreach and while loop in PHP for iterating over a DOMNodeList?

When iterating over a DOMNodeList in PHP, using a foreach loop is generally preferred over a while loop for simplicity and readability. The foreach loop automatically handles the iteration over each element in the DOMNodeList without the need for manual indexing or incrementing. This makes the code cleaner and easier to understand.

// Using foreach loop to iterate over a DOMNodeList
$dom = new DOMDocument();
$dom->loadHTML($html);

$elements = $dom->getElementsByTagName('p');

foreach ($elements as $element) {
    echo $element->nodeValue . "<br>";
}