How can the PHP code be optimized to avoid the mentioned problem of only being able to close certain layers?

The issue of only being able to close certain layers in PHP can be solved by using a recursive function to properly close all nested layers. By recursively iterating through the nested arrays and closing each layer, we can ensure that all layers are properly closed.

function closeAllLayers($arr) {
    foreach($arr as $key => $value) {
        if(is_array($value)) {
            echo "<div>";
            closeAllLayers($value);
            echo "</div>";
        } else {
            echo "<p>$value</p>";
        }
    }
}

$data = [
    "layer1" => [
        "layer2" => [
            "layer3" => "content"
        ]
    ]
];

closeAllLayers($data);