Skip to content
PHP Logo

How can nested arrays in PHP be iterated through using foreach loops without encountering "Array to string conversion" errors?

When iterating through nested arrays in PHP using foreach loops, you may encounter "Array to string conversion" errors if you try to directly output an array within the loop. To avoid this issue, you can check if the current element is an array before attempting to output it. If it is an array, you can recursively iterate through it.

php
<?php
function recursiveArrayIteration($array){
    foreach($array as $element){
        if(is_array($element)){
            recursiveArrayIteration($element);
        } else {
            echo $element . "<br>";
        }
    }
}

$array = array(
    1,
    2,
    array(
        3,
        4,
        array(
            5,
            6
        )
    )
);

recursiveArrayIteration($array);
?>