Introduction

Hello there! Are you ready to enhance your PHP programming skills with an exciting exercise? In this unit, we are diving into the world of matrices. More specifically, we'll be transposing a given matrix. Let's embark on this matrix manipulation adventure without delay!

Task Statement

To begin, let's elaborate on the task at hand. You are required to write a PHP function named transformMatrix(). This function will accept a 2D array (which represents a matrix) that contains integers as inputs. Your responsibility is to return another 2D array, which is the transposed version of the given matrix.

Remember, when we mention "transposing a matrix," we are referring to the process of switching its rows and columns. In other words, all the rows of the original matrix should convert into columns in the transposed matrix, and vice versa.

For instance, if the original matrix (input 2D array) is:

PHP
$matrix = [
    [1, 2, 3],
    [4, 5, 6]
];

Then the transposed matrix (output 2D array) will be:

PHP
$transposed = [
    [1, 4],
    [2, 5],
    [3, 6]
];

It is vital for your result to maintain the integrity of the data type that is present in the original matrix. In simpler terms, the values seen in the input matrix are integers, and they should remain integers in the output matrix as well.

Solution Building: Step 1
Solution Building: Step 2

The subsequent step is to create a "placeholder" for the transposed matrix that aligns with its required dimensions. This will be a new 2D array, but with the number of rows and columns swapped. Initially, this matrix can be populated with all zeros.

function transformMatrix($matrix) {
    $rows = count($matrix);
    $cols = $rows > 0 ? count($matrix[0]) : 0;
    $result = array_fill(0, $cols, array_fill(0, $rows, 0));
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal