What are some best practices for iterating over arrays in PHP, especially when dealing with nested structures?

When iterating over arrays in PHP, especially when dealing with nested structures, it is important to use recursive functions to handle multi-dimensional arrays. This allows you to traverse through all levels of the array without missing any elements. Additionally, using foreach loops can simplify the process and make the code more readable.

function recursiveArrayIterator($array) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            recursiveArrayIterator($value);
        } else {
            // Do something with the value
            echo $value . "\n";
        }
    }
}

$array = [
    'key1' => 'value1',
    'key2' => [
        'subkey1' => 'subvalue1',
        'subkey2' => 'subvalue2'
    ]
];

recursiveArrayIterator($array);