What are the best practices for using multidimensional arrays in PHP to store and manipulate data for a matrix?

When working with multidimensional arrays in PHP to store and manipulate data for a matrix, it's important to properly initialize the array with the correct dimensions, access elements using nested loops, and use built-in array functions for manipulation. Additionally, keeping track of row and column indices is crucial for performing operations on specific elements within the matrix.

// Initialize a 2D matrix with specified dimensions
$rows = 3;
$cols = 3;
$matrix = array();
for ($i = 0; $i < $rows; $i++) {
    $matrix[$i] = array_fill(0, $cols, 0);
}

// Access and modify elements in the matrix
$matrix[0][0] = 1;
$matrix[1][1] = 2;

// Print the matrix
for ($i = 0; $i < $rows; $i++) {
    for ($j = 0; $j < $cols; $j++) {
        echo $matrix[$i][$j] . " ";
    }
    echo "\n";
}