What are the advantages of using iterators over nested foreach loops when working with multidimensional arrays in PHP?

When working with multidimensional arrays in PHP, using iterators can provide a more efficient and cleaner way to iterate through the array compared to using nested foreach loops. Iterators allow for more flexibility in how the array is traversed and can often lead to more readable code. Additionally, iterators can offer better performance compared to nested loops, especially when dealing with large arrays.

// Using iterators to iterate through a multidimensional array
$array = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));

foreach ($iterator as $value) {
    echo $value . " ";
}