How can memory usage be optimized when working with multidimensional arrays in PHP?

When working with multidimensional arrays in PHP, memory usage can be optimized by using generators instead of creating the entire array in memory. Generators allow you to iterate over the elements of the array without storing them all at once, which can be particularly useful when dealing with large datasets.

function generateMultidimensionalArray($rows, $cols) {
    for ($i = 0; $i < $rows; $i++) {
        $row = [];
        for ($j = 0; $j < $cols; $j++) {
            $row[] = $i * $j;
        }
        yield $row;
    }
}

foreach (generateMultidimensionalArray(3, 3) as $row) {
    foreach ($row as $value) {
        echo $value . " ";
    }
    echo "\n";
}